UPDATE not working right in while loop

Discussion in 'PHP' started by zdvdla, Feb 26, 2011.

  1. #1
    I am trying to get info from a table, add rows in that table, and put the added value back into the table in another field...I want to add field1 and field2 of every row and put the total in the total row.
    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 |
    +-----------+



    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 = '$values'");


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

    }

    ?>

    also note that if I put a INT in place of $values - the echo changes to match...why??

    PLEASE help...I have been working on this for 2 entire days....
     
    zdvdla, Feb 26, 2011 IP
  2. AsHinE

    AsHinE Well-Known Member

    Messages:
    240
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    138
    #2
    You should specify which row to update in your table like
    $sql=mysql_query("UPDATE table SET total = '$values' WHERE user_name='".$row['user_name']."'");
    Cause if you don't every record in the table will be updated
     
    AsHinE, Feb 27, 2011 IP