PDOStatement :: bindValue- SQLSTATE [HY093]:参数号无效

时间:2016-04-28 08:45:59

标签: php mysql pdo

从下面的准备好的声明中解决 SQLSTATE[HY093]: Invalid parameter number 问题。
我发现 $stmt->bindValue 存在问题。

准备好的声明& BindValue - 1

$stmt = $conn->prepare(
   'SELECT *
    FROM `gcm_notification` t1
    RIGHT JOIN (
        SELECT MAX(`id`) AS `latest` 
        FROM `gcm_notification` 
        WHERE `registration_id` = :registration_id 
        GROUP BY `post_id`) t2
    ON `t1`.`id` = `t2`.`latest`
    LEFT JOIN `posts` t3 ON `t1`.post_id = `t3`.ID
    WHERE `registration_id` = :registration_id
    GROUP BY `post_id`'
);

$stmt->bindValue(':registration_id', $registration_id, PDO::PARAM_STR);
$stmt->execute();

结果
SQLSTATE[HY093]: Invalid parameter number

准备好的声明& BindValue - 2

$stmt = $conn->prepare(
   'SELECT *
    FROM `gcm_notification` t1
    RIGHT JOIN (
        SELECT MAX(`id`) AS `latest` 
        FROM `gcm_notification` 
        WHERE `registration_id` = :registration_id 
        GROUP BY `post_id`) t2
    ON `t1`.`id` = `t2`.`latest`
    LEFT JOIN `posts` t3 ON `t1`.post_id = `t3`.ID
    WHERE `registration_id` = :registration_id
    GROUP BY `post_id`'
);

$stmt->bindValue(':registration_id', $registration_id, PDO::PARAM_STR);
$stmt->bindValue(':registration_id', $registration_id, PDO::PARAM_STR);
$stmt->execute();

结果
SQLSTATE[HY000]: General error: 2031

准备好的声明& BindValue - 3

$stmt = $conn->prepare(
   'SELECT *
    FROM `gcm_notification` t1
    RIGHT JOIN (
        SELECT MAX(`id`) AS `latest` 
        FROM `gcm_notification` 
        WHERE `registration_id` = :registration_id 
        GROUP BY `post_id`) t2
    ON `t1`.`id` = `t2`.`latest`
    LEFT JOIN `posts` t3 ON `t1`.post_id = `t3`.ID
    WHERE `registration_id` = :registration_id_1
    GROUP BY `post_id`'
);

$stmt->bindValue(':registration_id', $registration_id, PDO::PARAM_STR);
$stmt->bindValue(':registration_id_1', $registration_id, PDO::PARAM_STR);
$stmt->execute();

结果
SUCCESS

我不明白为什么准备好的声明& BindValue - 1 不起作用。 bindValue无法绑定2个:registration_id的相同参数?

所以,我认为我对第一点的假设是正确的,我复制并粘贴另一个bindValue并尝试哪个准备好的声明& BindValue - 2 。结果再次失败。

我认为可能是因为参数出现了冲突。因此,我创建了将参数重命名为registration_idregistration_id_1,这是准备好的声明& BindValue - 3 ,它正在运作。

有人会介意向我解释实际发生的事情吗?

谢谢你,并且非常了解。

1 个答案:

答案 0 :(得分:0)

感谢 @Jon Stirling

阅读PHP Manual上的评论后。

引自 william dot clarke at gmail dot com

  

当然,如果你想以你应该使用的方式使用预备语句   第二个例子中的语法:

     

例如。

     

代替:select id,name from demo_de where name LIKE:name OR   name =:name

     

使用:从demo_de中选择id,名称LIKE?或者姓名=?

     

我相信你应该使用不同的命名参数   (name,name1)或匿名参数(?s)

他在9年前回答了我的问题。

希望这篇文章能帮助那些正在寻找答案的人。

相关问题