Use mysql_fetch_array and UPDATE for a while during the loop

I am trying to extract data from one table, compare the columns with a variable, then if they match, add them and update the field in another table. UPDATE seems to work only once inside the while loop and puts the value of this time on every row of this column throughout the table. It is strange when I repeat it, all values ​​are correct (unique) .. but only when I echo ... when I look at a table with a terminal, all rows of this column are identical. I read that you cannot use 2 queries at a time ... then again ... I read that you can, if the first one is outside the loop ... please help ...

I want to add field1 and field2 of each row and put the total in the total row.

understands the code ....

<?php

require("connection.php");


mysql_select_db("database", $connection);
echo "<br />";

$result = mysql_query("SELECT * FROM table");

while($row = mysql_fetch_array($result))
{

$values = ($row['field1'] + $row['field2']);

echo "values = " . $values;


$sql=mysql_query("UPDATE table SET total_val = '$values'");


echo $row['user_name'] . " " . $values;
echo "<br />";

}

?>

That's what the echo gives me

Susan 14

Mary 18

Bob 13

Sam 21

heres database

mysql> SELECT total_val FROM table;

+-----------+
| total_val |
+-----------+
| 21 |
| 21 |
| 21 |
| 21 |
+-----------+

ech totals are exactly what I want. I just need them to fit inside the total_val column.

+3
source share
2 answers

Update a specific (current) row in a loop while

He currently does this when while reaches the loop at the end of the iteration, he has a total of 21 and updates the table with a value of 21, therefore, all rows contain 21.

Your Query update updates all rows every time put here a condition for a unique identifier for the update

$sql=mysql_query("UPDATE table SET total_val = '$values' WHERE id=$row['id']");
+1
source

The current query updates all rows in the database.

Try the following:

$sql=mysql_query("UPDATE table SET total_val = '$values' WHERE id=".$row['id']);
0
source

Source: https://habr.com/ru/post/1795024/


All Articles