在对 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]:参数编号无效
准备好的语句和 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]:一般错误: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();
结果
成功
我不明白为什么 Prepared Statement & BindValue - 1 不起作用。 bindValue
不能绑定(bind) 2 个相同的参数 :registration_id
?
因此,我假设我对第一点的假设是正确的,我复制并粘贴了另一个 bindValue
并尝试使用 Prepared Statement & BindValue - 2。结果又失败了。
我猜可能是因为参数有冲突。因此,我将参数重命名为 registration_id
和 registration_id_1
,即 Prepared Statement & BindValue - 3 并且它正在运行。
有人介意向我解释一下到底发生了什么吗?
谢谢你,非常感谢。
最佳答案
感谢@Jon Stirling,
阅读关于 PHP Manual 的评论后.
引自william dot clarke at gmail dot com
Surely if you want to use prepared statements that way you should use the syntax in the second example:
eg.
instead of: select id,name from demo_de where name LIKE :name OR name=:name
use: select id,name from demo_de where name LIKE ? OR name=?
I believe you are supposed to either use distinct named parameters (name, name1) OR anonymous parameters (?s)
他大约在 9 年前回答了我的问题。
希望这篇文章对正在寻找答案的人有所帮助。
关于php - PDOStatement::bindValue- SQLSTATE[HY093]:参数编号无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909605/