简体   繁体   中英

strings do not escape when use mysql_real_escape_string or addslashes in mysql

i use mysql_real_escape_string php function for escape data recieved from a form. my code for recieve form data is :

$std_id     =   mysql_real_escape_string($_POST['std_id']);
$name       =   mysql_real_escape_string($_POST['name']);
$family     =   mysql_real_escape_string($_POST['family']);

for example if enter O'reilly string in name form field , this function work fine and my query done too.but when i go to mysql and my table , see that this string is inserted like O'reilly and not O\\'reilly . my query is :

$sql    =   "insert into student set 
            std_id  =   $std_id,
            name    =   '$name',
            family  =   '$family',
            ";

this happens when use addslashes() function too.

This is exactly what is supposed to happen. You want to insert the string O'reilly into the database, not O\\'reilly , right?

The slashes merely tell MySQL that the next ' is supposed to be a literal apostrophe, and not the apostrophe/single quote denoting the end of the string.


PS: You might want to consider using PDO and prepared statements , which offer a much cleaner syntax.

That's the point. mysql_real_escape_string is only there to make sure the query syntax is correct . This query syntax would be incorrect:

INSERT INTO ... name = 'O'Reilly'

The string terminator ' is ambiguous/misplaced.
Escaped, this becomes:

INSERT INTO ... name = 'O\'Reilly'

Now the syntax is unambiguous, the ' after O is not the string terminator, it's a literal value. That's all mysql_real_escape_string is supposed to do. You do not want the value as "O\\'Reilly" in your database, because that's garbage.

You should read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM