In my PHP page, I have a while loop that displays the name and price of products. I want to get the sum of all the price values in my loop. This is how the relevant sections of my code look at the moment:

while ( $row = mysql_fetch_array($result) ) {
$price = $row["Price"];

$name = $row["Name"];
$total = $price + $price;
echo("</td><td>" . $name . "</td><td>$ " . $price . "</td></tr>");
}
echo ("<tr><td>Total</td><td>$ " . $total . "</td></tr>");

However, what happens when I test my page, is that it multiplies the last price value in the while loop by 2, rather than add up all the different price values. What should I do? Help would be appreciated.

    Hi,

    try:

    $total = 0;
    while ( $row = mysql_fetch_array($result) ) {
    $price = $row["Price"];

    $name = $row["Name"];
    $total += $price;
    echo("</td><td>" . $name . "</td><td>$ " . $price . "</td></tr>");
    }
    echo ("<tr><td>Total</td><td>$ " . $total . "</td></tr>");

    firemouse2001

      why don't make the sum from the query:

      $query="select sum(PRICE) as suma from PRICES";
      $result=mysql_query($query);
      $row=mysql_fetch_array($result);
      $total=$row[0];

      this reduces the resources you use!

      hope this help.

      Happy coding!

      Sabbagh

        It worked! you're a star. Thanks.

        Mayan

          Write a Reply...