Andrea_86
Andrea_86

Reputation: 527

MySQL update multiple rows via PHP

I have to update the same value of multiple rows in a table and i would like to avoid multiple mysql_query using a foreach loop that scan every value of an array. I try to explain using an example. This is the solution of the problem using a foreach loop

$array=array(1,2,3);
foreach($array as $val){
$sql = "UPDATE mytable SET val_to_update = XX WHERE id = $val";
mysql_query($sql);
}

I didn't like to start hammering database with a crazy number of queries, because the number of element of the array is not fixed, and can also be large. I have considered using the IN clause of SQL language but without knowing the number of parameters can not seem to find a solution. Thinked at something like this, but I do not know if it is achievable:

$sql= "UPDATE Illustration SET polyptychID = $id_polyptych WHERE illustrationID IN (?,?,?);

and then bind all the parameters using a foreach loop for scan the array of parameters. The problem, as I said, is that i don't know the number, so i can't place the right number of ? in sql query and, if I'm not mistaken, the number of occurrences of ? parameters must be the same as the binded parameters. Anyone have solved a problem like this?

Upvotes: 2

Views: 1792

Answers (1)

eroteev
eroteev

Reputation: 610

If you are sure, that the array is containing integers, why don't you do it like this:

$array=array(1,2,3);
if (sizeof($array) > 0 {
  $sql = "UPDATE mytable SET val_to_update = XX WHERE id IN(".implode(',', $array).")";
  mysql_query($sql);
}

If you want to use prepared statement you could create your sql using this code:

$array=array(1,2,3);
    if (sizeof($array) > 0 {
       $placeholders = array();
       for($i=0; $i<sizeof($array); $i++) {
         $placeholders[] = '?';
       }
      $sql = "UPDATE mytable SET val_to_update = XX WHERE id IN(".implode(',', $placeholders).")";
  // .....
}

If the values in the $array exists in another table you could use something like this:

$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN (SELECT id FROM another_table WHERE condition = 1)";

Upvotes: 1

Related Questions