For example, I have two data on my table:
| ID | Name | Age |
| 1 | Steve | 25 |
| 2 | Bob | 28 |
When i updating one value (for example: change "Bob" to "George"), it changes all value. This is the result:
| ID | Name | Age |
| 1 | George | 28 |
| 2 | George | 28 |
How to updating multiple rows in one query? To collect values, I use for loop like this:
<?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.
Column values on multiple rows can be updated in a single UPDATE statement if the condition specified in WHERE clause matches multiple rows. In this case, the SET clause will be applied to all the matched rows.
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
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..!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With