如何在一个查询中更新多行(使用for循环)


How to update multiple rows in one query (using for loop)

例如,我的表上有两个数据:

| nbsp ID nbsp| nbsp 名称 nbsp| nbsp 年龄 nbsp|


| nbsp 1 nbsp nbsp| nbsp Steve nbsp| nbsp nbsp;25 nbsp 
| nbsp 2 nbsp nbsp| nbsp Bob nbsp nbsp  nbsp nbsp;28 nbsp 

当我更新一个值(例如:将"Bob"更改为"George")时,它会更改所有值。结果如下:
| nbsp ID nbsp| nbsp 名称 nbsp| nbsp 年龄 nbsp|


| nbsp 1 nbsp nbsp| nbsp 乔治 nbsp| nbsp nbsp;28 nbsp 
| nbsp 2 nbsp nbsp| nbsp 乔治 nbsp| nbsp nbsp;28 nbsp 

如何在一个查询中更新多行?为了收集值,我使用这样的循环:

<?php
...
$id_array = $_POST['id'];
$name_array = $_POST['name'];
$age_array = $_POST['age'];
$id = array();
$name = array();
$age = array();
for ($i = 0; $i < count($id_array); $i++) {
//count($id_array) --> if I input 4 fields, count($id_array) = 4)
   $id[] = mysql_real_escape_string($id_array[$i]);
   $name[] = mysql_real_escape_string($name_array[$i]);
   $age[] = mysql_real_escape_string($age_array[$i]);                    
}
mysql_query("UPDATE member SET name = '$name', age = '$age' WHERE id = '$id'");
}
...
?>

你能帮我吗?非常感谢。

在循环中构造查询:

<?php
...
$id_array = $_POST['id'];
$name_array = $_POST['name'];
$age_array = $_POST['age'];
for ($i = 0; $i < count($id_array); $i++) {
//count($id_array) --> if I input 4 fields, count($id_array) = 4)
   $id = mysql_real_escape_string($id_array[$i]);
   $name = mysql_real_escape_string($name_array[$i]);
   $age = mysql_real_escape_string($age_array[$i]);
   $query .= "UPDATE member SET name = '$name', age = '$age' WHERE id = '$id';";
}
mysql_query($query);
}
...
?>

希望能有所帮助。。!

问题的答案
MySQL会更新所有与WHERE子句匹配的行,因此要更新多个具有相同值的行,应该使用匹配所有行的条件。若要更新所有行,请不要设置任何where子句。若要更新具有不同值的多行,则不能,请使用多个查询。

问题的答案
在您的代码中,$id、$name和$age是数组,因此您不能在字符串中使用它,这将不起作用。您应该在FOR循环中进行更新。我建议您尽量尊重面向资源的原则,即所有属性都分配给它们的项(使用关联数组或对象)。如果你不检查结果,你可以使用分号在一个查询中完成所有查询。