jeff5656 Posted July 20, 2010 Share Posted July 20, 2010 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); Quote Link to comment https://forums.phpfreaks.com/topic/208249-help-with-array_sum/ Share on other sites More sharing options...
PFMaBiSmAd Posted July 20, 2010 Share Posted July 20, 2010 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? Quote Link to comment https://forums.phpfreaks.com/topic/208249-help-with-array_sum/#findComment-1088422 Share on other sites More sharing options...
tomtimms Posted July 20, 2010 Share Posted July 20, 2010 I agree, why not just use $q = "select SUM(num_hours) from timesheet "; Quote Link to comment https://forums.phpfreaks.com/topic/208249-help-with-array_sum/#findComment-1088424 Share on other sites More sharing options...
jeff5656 Posted July 20, 2010 Author Share Posted July 20, 2010 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 />"; } Quote Link to comment https://forums.phpfreaks.com/topic/208249-help-with-array_sum/#findComment-1088428 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.