Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2010
    Posts
    136

    Unanswered: SUM values inside foreach and while loop

    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 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
    The correct output should be: 70
    Any help is highly appreciated.
    Thank you very much..
    Last edited by newphpcoder; 04-27-12 at 23:35.

  2. #2
    Join Date
    Nov 2004
    Location
    out on a limb
    Posts
    13,692
    Provided Answers: 59
    what datatype is WorkingDays

    my guess is that its going to be a datetime, and if so you understand how databases store dates. (usually its a a number of ticks from an arbitrary point in time).
    I'd rather be riding on the Tiger 800 or the Norton

  3. #3
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    SUM values inside foreach and while loop

    i notice you've now created a separate table to store your 3 months...

    http://www.dbforums.com/mysql/167826...ve-months.html

    this is sad... sad
    Last edited by r937; 04-28-12 at 08:11.
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •