php prepared statement SQLSTATE [42000]:语法错误或访问冲突:1064

时间:2013-06-16 16:15:46

标签: php mysql pdo syntax-error prepared-statement

我正在尝试更改为准备好的语句,但一直收到以下错误:

警告:PDO :: query():SQLSTATE [42000]:语法错误或访问冲突:1064您有一个    SQL语法错误;检查与您的MySQL服务器版本对应的手册,以便在':fname AND 附近使用正确的语法

以下是使用的代码:

$street = 'astreet';
$lname = 'alname';
$fname = 'afname';
$list = '1,2,3,4,5';

   $var = 'admin';  

   $db = new PDO("mysql:dbname=customers;host=localhost",$var,$var);

   $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE :fname AND `last_name` LIKE :lname AND `street_name` LIKE :street";

   $stmt = $db->prepare($sql);

   $stmt->execute(array(':street' => $street));
   $stmt->execute(array(':fname' => $fname));
   $stmt->execute(array(':lname' => $lname));

   $result = $db->query($sql);



foreach ($result as $row) {

        echo $row['post_code'];

              }

如果我正常运行查询 - 不是准备好的问题,它运行正常 - 只有当我开始将:变量添加到查询中时我才会收到错误

是否有任何代码缺失/不正确?

由于

2 个答案:

答案 0 :(得分:1)

$stmt = $db->prepare($sql);

$stmt->execute(array(':street' => $street));
$stmt->execute(array(':fname' => $fname));
$stmt->execute(array(':lname' => $lname));

您正在运行相同的查询三次,每次都使用不同的参数。您需要运行查询:

$stmt = $db->prepare($sql);

$stmt->execute(array(':street' => $street, ':fname' => $fname, ':lname' => $lname));

一次性传递所有三个参数。

编辑添加:

您还可以尝试显式绑定参数:

$stmt = $db->prepare($sql);

$stmt->bindParam(':street', $street);
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);

$stmt->execute();

或者将它们添加为数组:

$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE ? AND `last_name` LIKE ? AND `street_name` LIKE ?";
$stmt = $db->prepare($sql);

$stmt->execute(array($fname, $lname, $street));

答案 1 :(得分:0)

据我所知,你必须在SQL中转义字符串。 所以我会替换

$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE :fname AND `last_name` LIKE :lname AND `street_name` LIKE :street";

通过

$sql = "SELECT * FROM `table` WHERE `id` in ($list) AND `first_name` LIKE ':fname' AND `last_name` LIKE ':lname' AND `street_name` LIKE ':street' ";