Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.