Forum Moderators: coopster

Message Too Old, No Replies

Calculate total value of rows returned in MySQL query

         

forefront

11:58 pm on Sep 17, 2004 (gmt 0)

10+ Year Member



Hi,

I am pulling data from a MySQL database. I want to print out all individual rows, then total them. My use of arrays and sum of those arrays has me baffled. I want to print out one total value that sums all data from field "sales_total"

The following prints the LAST row in the result set only.

Help!
Thank you.


<?
$result = mysql_query ("SELECT query goes here");
$myrow=mysql_fetch_array($result);

if ($myrow)
{

print "<ul>

$myarray = array($myrow ["sales_total"]);
$sum = array_sum($myarray);

do
{
$salestotal= $myrow ["sales_total"];

print "<li>$salestotal</li>";

}
while ($myrow=mysql_fetch_array($result));
print "</ul>$sum\n";

}

else
{
print "<h1>No results</h1>\n";
}
?>

killroy

12:17 am on Sep 18, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



you either loop through all rows and do your own sum, or, if it's a quick query, run it again to sum all rows.

SN

forefront

1:47 am on Sep 18, 2004 (gmt 0)

10+ Year Member



I am non-the-wiser.

Where/how would that go? An example would help me.

Thanks.

coopster

3:56 pm on Sep 18, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Your loop logic is what is causing your problems here. You need to do your totaling inside the loop, not outside of it. However, even if you were to move it inside the loop, you would be assigning only the current row value to a brand new array each time and totaling that would only give you the total of the current, or in this case, the last row. Try restructuring your logic:
$result = mysql_query('SELECT sales_total FROM table'); 
if (mysql_num_rows($result) > 0) {
print '<ul>';
$sum = array(); // initialize
while ($myrow = mysql_fetch_array($result)) {
$sum[] = $myrow['sales_total']; // sum
$salestotal= $myrow['sales_total'];
print "<li>$salestotal</li>";
}
$sum = array_sum($sum);
print "</ul>$sum\n";
} else {
print "<h1>No results</h1>\n";
}

forefront

6:18 am on Sep 19, 2004 (gmt 0)

10+ Year Member



Thank you, that worked perfectly.