PHP:无法将单引号字符串传递给mysqli查询

时间:2013-10-06 15:15:33

标签: php

我用这个简单的事情争了好几个小时:

$var=var;    
$result = "SELECT column1, column2 FROM $db WHERE column3 = '$var' ";

我得到的错误是:你的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第1行的'\'var \''附近使用正确的语法

名称是正确的,它适用于mysql查询。想想我尝试了所有可能的引用选项,出了什么问题?

更新:根据要求,我使用了转义,但错误仍然相同

$var=var;   
$var = $conn->real_escape_string($var);
$result = "SELECT column1, column2 FROM {$db} WHERE column3 = '{$var}' ";

2 个答案:

答案 0 :(得分:0)

必须有

$var = $mysqli->real_escape_string($var);
$sql = "SELECT column1, column2 FROM {$db} WHERE column3 = '{$var}' ";

而不是:

$result = "SELECT column1, column2 FROM $db WHERE column3 = '$var' ";
$result = $mysqli->real_escape_string($result) ; //Totally wrong.

答案 1 :(得分:0)

我在mysql控制台中使用错误的SQL查询进行了测试:

 mysql>  SELECT column1, column2 FROM WHERE column3 = 'varvalue';

它给出了这个错误:

ERROR 1064 (42000): 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 'WHERE column3 = 'varvalue'' at line 1

实际上缺少表名。我猜你的变量$ db可能是null / empty / unset。

请尝试:

$db = "mytable";
$var = "varvalue";
$result = "SELECT column1, column2 FROM $db WHERE column3 = '$var' ";