Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do multiple updates in a single SQL query?

Tags:

sql

php

where

I have an SQL query that takes the following form:

UPDATE foo
SET flag=true
WHERE id=?

I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...

foreach($list as $item){  
    $querycondition = $querycondition . " OR " . $item;  
}

... and using the output in the WHERE clause?

like image 798
Esa Avatar asked Sep 02 '08 15:09

Esa


2 Answers

This would achieve the same thing, but probably won't yield much of a speed increase, but looks nicer.

mysql_query("UPDATE foo SET flag=true WHERE id IN (".implode(', ',$list).")");
like image 93
Chris Bartow Avatar answered Sep 22 '22 03:09

Chris Bartow


You should be able to use the IN clause (assuming your database supports it):

UPDATE foo SET flag=true WHERE id in (1, 2, 3, 5, 6)

like image 23
matt b Avatar answered Sep 23 '22 03:09

matt b