First of all: don't use mysql_escape_string, it is deprecated, use mysql_real_escape_string instead.
The difference between mysql_real_escape_string and addslashes is:
Difference 1:
addslashes does not know anything about the character set of the MySQL connection. If you pass a string containing a byte encoding other than the MySQL connection you are using, it will happily escape all bytes whose values are the characters ', ", and x00. If you are using Unlike other characters in 8-bit and UTF-8, the values of these bytes are not necessarily all represented by the characters ', ", and x00. The possible result is that an error occurs after MySQL receives these characters.
If you want to fix this bug, you can try using the iconv function to convert the variable to UTF-16, and then use addslashes to escape.
This is one of the reasons not to use addslashes for escaping.
Difference 2:
Compared with addslashes, mysql_real_escape_string also escapes r, n and x1a. It seems that these characters must be told to MySQL correctly, otherwise you will get wrong query results.
This is another reason not to use addslashes for escaping.
addslashes V.S. mysql_real_escape_string
In GBK, 0xbf27 is not a legal multi-character character, but 0xbf5c is. In a single-byte environment, 0xbf27 is treated as 0xbf followed by 0x27(‘), while 0xbf5c is treated as 0xbf followed by 0x5c().
A single quote escaped with a backslash cannot effectively prevent SQL injection attacks against MySQL. If you use addslashes, then I (the attacker, the same below) is very lucky. I just inject something like 0xbf27, and then addslashes it to 0xbf5c27, a legal multibyte character followed by a single quote. In other words, I can successfully inject a single quote regardless of your escaping. This is because 0xbf5c is treated as a single-byte character, not a double-byte character.
In this demonstration, I will be using MySQL 5.0 and the mysqli extension for PHP. If you want to try it, make sure you use GBK.
Create a table named users:
Despite using addslashes, I can successfully log in without knowing my username and password. I can easily exploit this vulnerability to perform SQL injection.
To avoid this vulnerability, use mysql_real_escape_string, prepared statements (Prepared Statements, "parameterized queries"), or any mainstream database abstraction library.