i am trying to pull data from one table, compare columns to a variable, then if they match, add them and update a field on another table. It seems that the UPDATE only works once inside the while loop, and puts the value of that one time in every row of that column throughout the table. Odd thing is, when I echo it, all the values are correct (unique)..but only when I echo…when I look at table with terminal, all the rows of that column are identical. I have read that you cannot use 2 query at a time…then again…I have read that you can, if the first one is outside the loop…please help…
I want to add field1 and field2 of every row and put the total in the total row.
heres 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 />";
}
?>
Heres what the echo gives me
Susan 14
Mary 18
Bob 13
Sam 21
heres the database
mysql> SELECT total_val FROM table;
+-----------+
| total_val |
+-----------+
| 21 |
| 21 |
| 21 |
| 21 |
+-----------+
the ech totals are exactly what I want. I just need them put inside the total_val column.
Update the specific (current) row in the
whileloopCurrently it is doing like this when while loop reach at the end of iteration it has the total 21 and it updates table with value 21 hence all the rows contains 21.
Your update Query is updating all rows every time
put here condition for the unique id to update