What is the difference between mysql_real_escape_s

2020-02-26 09:22发布

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)

标签: php
5条回答
▲ chillily
2楼-- · 2020-02-26 09:52

case 1:

$str = "input's data";

print mysql_real_escape_string($str);      input\'s data

print addslashes($str);                    input\'s data;

case 2:

$str = "input\'s data";

print mysql_real_escape_string($str);      input\'s data

print addslashes($str);                    input\\'s data;
查看更多
该账号已被封号
3楼-- · 2020-02-26 09:56

It seems that mysql_real_escape_string is binary-safe - the documentation states:

If binary data is to be inserted, this function must be used.

I think it's probably safer to always use mysql_real_escape_string than addslashes.

查看更多
贼婆χ
4楼-- · 2020-02-26 09:59

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.

查看更多
Lonely孤独者°
5楼-- · 2020-02-26 10:00

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

查看更多
Viruses.
6楼-- · 2020-02-26 10:10

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

string addslashes ( string $str )
Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

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.

查看更多
登录 后发表回答