S
S
Sannis2011-02-02 00:39:34
MySQL
Sannis, 2011-02-02 00:39:34

mysql_real_escape_string vs mysql_escape_string

According to the documentation, you should only use the mysql_real_escape_string function.
As far as I understand, this is mainly due to the use of Unicode and is really justified.

Question: how often mysql_escape_string is wrong and is it possible in languages ​​with native unicode support to use your own implementation like:

/**
 * Escape string for mysql. Don't use native function,
 * because it doesn't work without connect.
 */
exports.escapeStr = function(str) {
    return str.replace(/[\\"']/g, "\\$&").replace(/[\n]/g, "\\n")
                .replace(/[\r]/g, "\\r").replace(/\x00/g, "\\0");
};


UPD: The above code is not complete, it does not contain all the characters that need to be escaped . Let's assume that replace for \b, \t, \Z, _, % are also present:
exports.escapeStr = function(str) {
    return str.replace(/[\\"']/g, "\\$&").replace(/\n/g, "\\n")
                .replace(/\r/g, "\\r").replace(/\x00/g, "\\0")
                .replace(/\b/g, "\\b").replace(/\t/g, "\\t")
                .replace(/\x32/g, "\\Z") // \Z == ASCII 26
                .replace(/_/g, "\\_").replace(/%/g, "\\%");
};

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Anatoly, 2011-02-02
@taliban

I think you are wrong more often than those who made the mysql_real_escape_string function. I do not want to say that you are worse at programming, but only that:
1 - this function uses not only Unicode, but the current connection encoding.
2 — those who wrote this function may have stepped on more than one rake that you don’t know about
3 — these four replacements may not be enough for complete peace of mind
4 — it simply works faster

S
shagguboy, 2011-02-02
@shagguboy

pass at last to bind parameters. in addition to the absence of such problems, there will be no re-parsing of the request with each execution.

V
Vitaly Zheltyakov, 2011-02-02
@VitaZheltyakov

Here it is necessary to approach from the outside - Are prohibited symbols used in the project?
Personally, for example, in my current project, these characters are not used, so I simply banned them on the white list, and generally refused the mysql_real_escape_string function as unnecessary.

L
lashtal, 2011-02-02
@lashtal

Are you looking on stackoverflow? =)
goo.gl/LgdZi
Brief retelling: you can't, because for escaping you need information about the encoding of the connection to the database.
Below, however, is a supposedly safe function.

P
pentarh, 2011-02-02
@pentarh

If latin1, then what for this real_escape.
In redneck code, there are usually a dozen or two escapes per script. Ato and more. And if you use real_escape where it is not needed, then it will be 1 request to the database for 1 real_escape. At high loads, it can stand on the handbrake.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question