views:

157

answers:

3

I use Postgresql + PHP.

Say I have this table:

Books ( id, title, year )

and this array of titles in PHP:

$titles = array ("bible","kafka","Book of Eli");

now I want update all rows where the title is in the $titles array above.

So I need a query like this:

UPDATE books SET year = '2001-11-11' WHERE title is in $titles;

Is is possible with one single query ? Or do I need to use FOR loop ?

+4  A: 

It's possible, you were actually quite close.

For the SQL, the syntax looks like this:

UPDATE books SET year = '2001-11-11' WHERE title IN ('bible','kafka','Book of Eli');

To generate that using PHP, you'll want to do something like this:

$query = "UPDATE books SET year = '2001-11-11' WHERE title IN ('" . implode("','", $titles) . "');'";

The PHP implode() function joins array elements together using a string, so I put ',' between all of them, with the initial and final ' being put in the string manually.

Note that this will currently fail if any of the titles contain an apostrophe. If that's a possibility you will need to escape those.

Chad Birch
Looks like you beat me to the post.
Robert Durgin
Good answer, but the php manual says: "The query string should not end with a semicolon."
PHP_Jedi
DON'T FORGET to call pg_escape_string() on those titles before imploding them!
intgr
+1  A: 

You can use the implode() function, which will let you turn the array into a comma-separated string:

$titles = array ("bible","kafka","Book of Eli");
$comma_separated = implode(",", $array)
$sql = "UPDATE books SET year = '2001-11-11' WHERE title is in (" . $comma_separated .")"
Robert Durgin
You didn't quote the strings, wouldn't currently work.
Chad Birch
+1  A: 

What about

$sql = "UPDATE books SET year = '2001-11-11' WHERE title in ('".implode("','",$titles)."')";
PHP_Jedi
Forgot the first/last quotes, your string would look like: `WHERE title IN (bible','kafka','Book of Eli)`
Chad Birch
I think you misssed the opening and closing ' you've got the ones between the imploded values.
TooManyCooks
Thats true. Fixed. Thanks
PHP_Jedi