Jump to content

SUM values inside foreach and while loop


newphpcoder

Recommended Posts

Hi..I have table which has a data so_month:FromMonth : 5ToMonth : 7and I have table working_days:MonthNameMayJunJulMonthNumber050607WorkingDays232423Now I have function to get the 3 consecutive months from FromMonth to ToMonth , which as you can see from May to JulNow I have problem in getting the SUM of Working days.here is my code:

<?php  $sql = "SELECT FromMonth, ToMonth FROM so_month";$res = mysql_query($sql,$con);$row = mysql_fetch_assoc($res);$FromMonth = $row['FromMonth'];$ToMonth = $row['ToMonth'];function monthNames($from, $to){   $range=array();   for($i=$from; $i<=$to; $i++){		   $range[$i]=date('M', mktime(0,0,0,$i));   }    return $range;}$month_ = implode("' ', ",monthNames($FromMonth,$ToMonth));foreach( monthNames($FromMonth, $ToMonth) as $month){$sql = "SELECT MonthName, SUM(WorkingDays) AS WorkingDays FROM working_days WHERE MonthName IN ('$month') GROUP BY MonthName";$res = mysql_query($sql, $con);while($row = mysql_fetch_array($res)){$WorkingDays = $row['WorkingDays'];}echo $WorkingDays;}?>

the output of this code is:232423and when I change this line:$WorkingDays = $row['WorkingDays'];to$WorkingDays += $row['WorkingDays'];the output is:234770The correct output should be: 70Any help is highly appreciated.Thank you very much..

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...