...

View Full Version : SUM values inside foreach and while loop



newphpcoder
04-28-2012, 03:28 AM
Hi..

I have table which has a data so_month:

FromMonth : 5
ToMonth : 7

and I have table working_days:

MonthName
May
Jun
Jul
MonthNumber
05
06
07
WorkingDays
23
24
23

Now I have function to get the 3 consecutive months from FromMonth to ToMonth , which as you can see from May to Jul

Now 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:

232423

and when I change this line:

$WorkingDays = $row['WorkingDays'];
to
$WorkingDays += $row['WorkingDays'];

the output is:

234770

I correct output should be: 70

Any help is highly appreciated.

Thank you very much..

newphpcoder
04-28-2012, 04:17 AM
Where are you initialising the value of $WorkingDays before the WHILE loop?

Also, there might be a problem with your table data.

Have a look at each value of $row['WorkingDays'] using echo.




$WorkingDays = 0;

while($row = mysql_fetch_array($res)){

echo $row['WorkingDays'].'<br />';

$WorkingDays += $row['WorkingDays'];
}

echo $WorkingDays;



here is the output:

23
2324
2423
23



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum