我正在尝试获取一个 ID 号数组,并使用该 ID 号更新每一行。 PHP PDO 代码如下:
private function markAsDelivered($ids) {
$update = $this->dbh->prepare("
UPDATE notifications
SET notified = 1
WHERE notification_id IN (
:ids
)
");
$ids = join(',', $ids);
Logger::log("Marking the following as delivered: " . $ids, $this->dbh);
$update->bindParam(":ids", $ids, PDO::PARAM_STR);
$update->execute();
}
但是,当它运行时,只有列表中的第一项得到更新,尽管记录了多个 ID 号。我如何修改它以更新多行?
最佳答案
占位符只能代表一个原子值。它起作用的原因是因为 mysql 看到的值是 '123,456' 的形式,它将其解释为整数,但一旦遇到非数字部分(逗号)就会丢弃字符串的其余部分。
相反,做类似的事情
$list = join(',', array_fill(0, count($ids), '?'));
echo $sql = "...where notification_id IN ($list)";
$this->dbh->prepare($sql)->execute(array_values($ids));
关于PHP PDO : Array in Update SQL WHERE IN () clause,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560537/