0

I would like to run an update query for every row with a specific ID:

e.g.

$ids = array(111, 112, 113);
$query = "UPDATE mytable SET columnName = 'Y' WHERE id = :id1 or id = :id2 or id = :id3";
$stmt->bindParam(':id1', $ids[0], PDO::PARAM_INT);
$stmt->bindParam(':id2', $ids[1], PDO::PARAM_INT);
$stmt->bindParam(':id3', $ids[2], PDO::PARAM_INT);

This works fine if I know there are 3 ids to update, but how would I do this if the number of id fields is variable?

user1480951
  • 143
  • 2
  • 13

1 Answers1

0

Something like this would do the trick.

$ids = array(111, 112, 113);
$valueString = "";

foreach($ids as $key => $val) {
    $valueString .= ":id" . $key . " = " . $val;

    if (end($ids) != $val) {
        $valueString .= ", ";
    }
}

$query = "UPDATE mytable SET columnName = 'Y' WHERE ". $valueString;

foreach($ids as $key => $val) {
    $stmt->bindParam(':id' . $key, $val, PDO::PARAM_INT);
}
Dees Oomens
  • 4,554
  • 3
  • 29
  • 61