开发者

importance of link identifier in mysql_real_escape_string()

Why is it necessary to have a link identifier as an input when using mysql_real_escape_strin开发者_C百科g(). I know that the function should be used with MySQL queries, but the function is really just a string manipulation.


From the PHP manual:

Escapes special characters in the unescaped_string , taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

and:

If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

A connection is needed to determine the character set.


Have a read of http://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html

For example, if GBK character set is being used, it will not convert an invalid multibyte sequence 0xbf27 (¿’) into 0xbf5c27 (¿\’ or in GBK a single valid multibyte character followed by a single quote). To determine the proper escaping methodology mysql_real_escape_string() needs to know the character set used, which is normally retrieved from the database connection cursor.

Maybe as a consequence of this article but clearly after it the function mysql_set_charset() has been added to the mysql extension. The charset is a property of the mysql connection (resource).
If you have multiple connections you really should pass them to mysql_real_escape_string() (and always use mysql_set_charset() instead of SET NAMES).
If you don't pass the connection resource the function will use the last connection established by your script. If the charset of the two (or more connections) differ the result of real_escape_string() may be misinterpreted by the server (expecting another encoding and therefore different escaping rules).
And since it doesn't hurt to do so even if you have only one connection (can you say with absolute certainty that this will be so until the end of time?) just pass it always.


mysql_real_escape_string:

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜