简体   繁体   English

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

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

For example, I have two data on my table: 例如,我的桌子上有两个数据:

| | ID | ID | Name | 名称| Age | 年龄|


| | 1 | 1 | Steve | 史蒂夫| 25 | 25 |
| | 2 | 2 | Bob | 鲍勃| 28 | 28 |

When i updating one value (for example: change "Bob" to "George"), it changes all value. 当我更新一个值(例如:将“Bob”更改为“George”)时,它会更改所有值。 This is the result: 这是结果:
| | ID | ID | Name | 名称| Age | 年龄|


| | 1 | 1 | George | 乔治| 28 | 28 |
| | 2 | 2 | George | 乔治| 28 | 28 |

How to updating multiple rows in one query? 如何在一个查询中更新多行? To collect values, I use for loop like this: 为了收集值,我使用for循环如下:

<?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'");
}
...
?>

Can you help me? 你能帮助我吗? Thank you. 谢谢。

Construct your query within the loop: 在循环中构造您的查询:

<?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);
}
...
?>

Hope that helps..! 希望有帮助..!

Answer to your Question 回答你的问题
MySQL updates all rows matching the WHERE clause, so to update multiple rows with the same value, you should use a condition matching all rows. MySQL更新与WHERE子句匹配的所有行,因此要使用相同的值更新多个行,您应该使用匹配所有行的条件。 To update all rows, dont set any where clause. 要更新所有行,请不要设置任何where子句。 To update multiple rows with different values, you can't, use several queries. 要使用不同的值更新多个行,您不能使用多个查询。

Answer to your issue 回答你的问题
In your code, $id, $name and $age are arrays so you can not use it in a string, this will not work. 在你的代码中,$ id,$ name和$ age是数组,所以你不能在字符串中使用它,这是行不通的。 You should do the update in your FOR loop. 您应该在FOR循环中进行更新。 I advise you to try to respect resource oriented principe that all properties are assigned to their item (with associative array or object). 我建议你尝试尊重面向资源的原则,将所有属性分配给它们的项目(使用关联数组或对象)。 If you dont check the result, you could do all queries in one using a semi-colon. 如果您不检查结果,可以使用分号在一个查询中执行所有查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM