[thelist] mysql/php: using the sum() function...i think

Matt Warden mwarden at gmail.com
Sun Feb 6 01:57:00 CST 2005


On Sat, 5 Feb 2005 23:26:10 -0800, Roger H. <rogerharness at sbcglobal.net> wrote:
> then a while loop:
> $food=$row[0];
> $calories=$row[1];
> $carbs=$row[2];
> etc etc.
> then print the rows.
> Now I just want to be able to total up the calories and carbs at the bottom.
> I can do this at the mysql command line with:
> select SUM(calories) from my_table; or
> select SUM(carbs) from my_table;
> but i can't figure out how to do both, and more importantly, how to utilize
> this into my php/html.

If $row[0], $row[1], or $row[2] represent the values that you want to
sum, you do not need to query mysql again. Simply do something like

$caltotal = 0;
$carbtotal = 0;

// this is the while loop you already  have
while ($row = mysql_fetch_row($result))
       // .. your current code
       $carbtotal += $row[0]; // assuming 0 is carbs
       $caltotal += $row[1]; //assuming 1 is cals
} // end while

echo "<br />total carbs: $carbtotal<br />total cals: $caltotal";

If carbs and cals are not in your row, you will need to use a solution
like the one Mr. Gormley offered.


Matt Warden
Miami University
Oxford, OH, USA

This email proudly and graciously contributes to entropy.

More information about the thelist mailing list