[英]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. 我必须更新表中多个行的相同值,并且我想避免使用扫描数组中每个值的foreach循环使用多个mysql_query。 I try to explain using an example.
我尝试用一个例子来解释。 This is the solution of the problem using a foreach loop
这是使用foreach循环解决问题的方法
$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.
我曾考虑过使用SQL语言的IN子句,但在不知道参数数量的情况下似乎无法找到解决方案。 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. 然后使用foreach循环绑定所有参数以扫描参数数组。 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 ?
在sql查询中,如果我没记错的话,出现的次数是多少? parameters must be the same as the binded parameters.
参数必须与绑定的参数相同。 Anyone have solved a problem like this?
有人解决过这样的问题吗?
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: 如果要使用准备好的语句,则可以使用以下代码创建sql:
$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: 如果$ array中的值存在于另一个表中,则可以使用以下内容:
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN (SELECT id FROM another_table WHERE condition = 1)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.