简体   繁体   中英

Issue with mysql_real_escape_string

I have the following query:
SELECT * FROM ships WHERE shipCode="SP"
SELECT * FROM ships WHERE shipCode=\\"SP\\"

The first works fine, the second which is the result of calling mysql_real_escape_string on the first string, doesn't work and gives the useless error message #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\"SP\\"' at line 1 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\\"SP\\"' at line 1

What's wrong with it?

shipCode is a VARCHAR(2)

You're not supposed to call mysql_real_escape_string on the whole string. You use it only on the values you're concatenating into your query.

Wrong:

$query = 'SELECT * FROM ships WHERE shipCode="' . $var . '"';
$query = mysql_real_escape_string($query);

Right:

$query = 'SELECT * FROM ships WHERE shipCode="' . mysql_real_escape_string($var) . '"';

Even better: Prepared statements.

you need to have valid connection with mysql set up before you use mysql_real_escape string . do it like this

$attr="sp";
Select * from ships where shipcode = '" . mysql_real_escape_string($attr) . "';

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