Jump to content

help with array_sum


jeff5656

Recommended Posts

I want to add up all the hours in a field called "num_hours"

 

When I run this code I get a result of 8, even though if you add up the hours it comes to about 20.

Interestingly, there are 9 records - so it seems like my code is acting like mysql_num_rows()!

 

$q = "select num_hours from timesheet ";

$results = mysql_query ($q) or die (mysql_error());
$invarray = mysql_fetch_array ($results);
echo "tot hours =".array_sum($invarray);

Link to comment
https://forums.phpfreaks.com/topic/208249-help-with-array_sum/
Share on other sites

Each call to mysql_fetch_array(), fetched ONE (1) row from the result set. The while() loop you have seen in typical mysql code is there to iterate over all the rows in the result set.

 

Is there some reason you are not using the mysql SUM() function directly in your query to produce the same result?

Link to comment
https://forums.phpfreaks.com/topic/208249-help-with-array_sum/#findComment-1088422
Share on other sites

Oh I wasn't familiar with mysql SUM().  I looked it up and the following code works perfectly thanks!

 

$query = "SELECT user_id, SUM(num_hours) FROM timesheet GROUP BY user_id";
while($row = mysql_fetch_array($result)){
echo "Total ". $row['user_id']. " = ". $row['SUM(num_hours)'];
echo "<br />";
}

 

Link to comment
https://forums.phpfreaks.com/topic/208249-help-with-array_sum/#findComment-1088428
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.