PHP PDO: Array in Update SQL WHERE IN () clause

时间秒杀一切 提交于 2019-12-10 11:00:57

问题


I'm trying to take an array of ID numbers and update every row with that ID number. PHP PDO code follows:

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();
}

However, when this is run, only the first item in the list is getting updated, although multiple ID numbers are being logged. How do I modify this to update more than one row?


回答1:


A placeholder can only represent a single, atomic value. The reason it kinda works is because the value mysql sees is of the form '123,456' which it interprets as an integer, but discards the rest of the string once it encounters the non numeric part(the comma).

Instead, do something like

$list = join(',', array_fill(0, count($ids), '?'));
echo $sql = "...where notification_id IN ($list)";
$this->dbh->prepare($sql)->execute(array_values($ids));


来源:https://stackoverflow.com/questions/10560537/php-pdo-array-in-update-sql-where-in-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!