[英]How to update multiple rows with one single query
I use Postgresql + PHP. 我使用Postgresql + PHP。
Say I have this table: 说我有这张桌子:
Books ( id, title, year )
and this array of titles in PHP: 和PHP中的这个标题数组:
$titles = array ("bible","kafka","Book of Eli");
now I want update all rows where the title is in the $titles array above. 现在,我想更新标题在上述$ titles数组中的所有行。
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 ?
还是我需要使用FOR循环?
It's possible, you were actually quite close. 有可能,您实际上距离很近。
For the SQL, the syntax looks like this: 对于SQL,语法如下所示:
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: 要使用PHP生成该代码,您需要执行以下操作:
$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. PHP
implode()
函数使用字符串将数组元素连接在一起,因此我将','
放在所有元素之间,并将初始和最终'
手动放入字符串中。
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.
如果有这种可能,您将需要逃避这些。
You can use the implode() function, which will let you turn the array into a comma-separated string: 您可以使用implode()函数,该函数可让您将数组转换为逗号分隔的字符串:
$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 .")"
关于什么
$sql = "UPDATE books SET year = '2001-11-11' WHERE title in ('".implode("','",$titles)."')";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.