PHP的addlashes和mysql(i)_escape_string有什么区别? [英] What's the difference between PHP's addslashes and mysql(i)_escape_string?
问题描述
Possible Duplicate:
mysql_real_escape_string VS addslashes
如果他们做的不完全一样,有什么区别? MySQL查询中值的定界符是'
是吗?也许"
,但也用加号转义了.
If they don't do exactly the same, what's the difference? The delimiter for values inside a MySQL query is the '
isn't it? Or maybe the "
but that's also escaped with addslashes.
在其他数据库引擎中,我了解(并且肯定在诸如PDO之类的db包装器中),但是为什么有那么多人这么喜欢使用mysql(i)_escape_string而不是addlashes?
In other database engines I understand (and definitely inside a db wrapper like PDO), but why are so many people so adament on using mysql(i)_escape_string instead of addslashes?
推荐答案
首先:不使用mysql_escape_string
,它已被弃用(由于某种原因)!
First of all: do not use mysql_escape_string
, it is deprecated (for a reason)!
如果您必须支持通过mysql
扩展名连接到数据库的旧版应用程序(该扩展名已被弃用),请使用 mysqli
,其中已准备好的语句和绑定参数为转义用户输入提供了更健壮的机制.
If you have to support a legacy application that connects to the database through the mysql
extension (which has been deprecated), use mysql_real_escape_string
instead. Otherwise switch immediately to mysqli
, where prepared statements and bound parameters provide a more robust mechanism for escaping user input.
也就是说,可以通过阅读 mysql_real_escape_string
和 addslashes
:
That said, the answer can be found by reading the description of mysql_real_escape_string
and addslashes
:
差异#1
addslashes
对MySql连接编码一无所知.如果向其传递一个字符串,该字符串包含表示MySql连接使用的编码以外的编码的字节,则它将很高兴地转义具有字符值的所有字节 '
,"
,\x00
.如果您使用的不是8位编码和UTF-8编码,则这可能与所有字符 '
,"
,\
和\x00
不同.结果将是MySql接收的字符串将被破坏.
addslashes
does not know anything about MySql connection encodings. If you pass it a string containing bytes representing an encoding other than the encoding used by the MySql connection, it will happily escape all bytes having the values of the characters '
, "
, \
and \x00
. This may not be the same as all the characters '
, "
, \
and \x00
if you are using an encoding other than 8-bit encodings and UTF-8. The result will be that the string received by MySql will be corrupted.
要触发此错误,请尝试使用 iconv
来将您的变量转换为UTF-16,然后使用addslashes
对其进行转义.查看您的数据库收到了什么.
To trigger this bug, try using iconv
to convert your variable to UTF-16 and then escape it with addslashes
. See what your database receives.
这是为什么不应该使用addslashes
进行转义的原因之一.
This is one reason why addslashes
should not be used for escaping.
差异#2
与addslashes
相比,mysql_real_escape_string
还转义了字符\r
,\n
和\x1a
.与MySql交谈时,似乎也必须转义这些字符,否则可能会导致格式错误的查询
In contrast to addslashes
, mysql_real_escape_string
also escapes the characters \r
, \n
, and \x1a
. It appears that these characters have to be escaped as well when talking to MySql, otherwise a malformed query may be the result
这是不应使用addslashes
进行转义的另一个原因.
This is the other reason why addslashes
should not be used for escaping.
这篇关于PHP的addlashes和mysql(i)_escape_string有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!