mysql_real_escape_string
and addslashes
are both used to escape data before the database query, so what's the difference? (This question is not about parametrized queries/PDO/mysqli)
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
case 1:
case 2:
It seems that
mysql_real_escape_string
is binary-safe - the documentation states:I think it's probably safer to always use
mysql_real_escape_string
than addslashes.mysql_real_escape_string()
has the added benefit of escaping text input correctly with respect to the character set of a database through the optional link_identifier parameter.Character set awareness is a critical distinction.
addslashes()
will add a slash before every eight bit binary representation of each character to be escaped.If you're using some form of multibyte character set it's possible, although probably only through poor design of the character set, that one or both halves of a sixteen or thirty-two bit character representation is identical to the eight bits of a character
addslashes()
would add a slash to.In such cases you might get a slash added before a character that should not be escaped or, worse still, you might get a slash in the middle of a sixteen (or thirty-two) bit character which would corrupt the data.
If you need to escape content in database queries you should always use
mysql_real_escape_string()
where possible.addslashes()
is fine if you're sure the database or table is using 7 or 8 bit ASCII encoding only.mysql_real_escape_string
should be used when you are receiving binary data,addslashes
is for text input.You can see the differences here: mysql-real-escape-string and addslashes
They affect different characters.
mysql_real_escape_string
is specific to MySQL. Addslashes is just a general function which may apply to other things as well as MySQL.