Reputation: 1698
I am having a very annoying problem related to updating multiple table rows in a loop. My code updates only first row and not the others. In fact it throws an error while updating other rows.
Here is my prototype brief code to the point:
// This query returns multiple rows
$query = "SELECT * FROM `table_name` ...";
$rs = mysqli_query($con, $query);
if(mysqli_num_rows($rs) != 0)
{
while($row = mysqli_fetch_array($rs))
{
$column_name= $row['column_name'];
...
...
...
// This update query only updates first row which matches the given condition. On second loop, it throws an error.
$update = "UPDATE `table_name` SET `column_name` = '" . mysqli_real_escape_string($con, $column_name) . "', ... ";
$rs = mysqli_query($con, $update);
}
}
So my above code runs successfully only once. On second attempt, it outputs following error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\test\update.php on line 11
This is my first ever attempt to run update query in a loop. I never used it before. I think I might be doing it all wrong way. What would be the solution to fix my issue or any better way to achieve the same?
EDIT
OOPS!!! Again unnecessary $rs after update query and it drove me crazy!
Upvotes: 0
Views: 266
Reputation: 19777
You are overriding the $rs
value after the first update. So you can't do another mysqli_fetch_array($rs)
after that, because $rs
is not the result of the first mysqli_query()
.
$rs2 = mysqli_query($con, $update);
Upvotes: 2