mysql_real_escape_string的问题

时间:2012-03-06 01:58:59

标签: php mysql

我有以下疑问:
SELECT * FROM ships WHERE shipCode="SP"
SELECT * FROM ships WHERE shipCode=\"SP\"

第一个工作正常,第二个是在第一个字符串上调用mysql_real_escape_string的结果,不起作用并给出无用的错误消息#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

它出了什么问题?

shipCode是VARCHAR(2)

2 个答案:

答案 0 :(得分:4)

您不应该在整个字符串上调用mysql_real_escape_string。您只能在上使用它,并将其连接到查询中。

<强>错误:

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

右:

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

更好:Prepared statements.

答案 1 :(得分:0)

在使用mysql_real_escape字符串之前,您需要与mysql设置有效连接。这样做

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