1

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

警告: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'];

              }

如果我正常运行查询 - 不是准备好的状态,它工作正常 - 只有当我开始将:variables添加到查询时我才会收到错误

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

谢谢

4

2 回答 2

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

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

您运行相同的查询 3 次,每次使用不同的参数。您需要这样运行查询:

$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));
于 2013-06-16T16:24:42.230 回答
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' ";
于 2014-05-02T22:08:40.477 回答