Search code examples
phploopsnested-loops

Curious why loop doesn't show second day of data:


I am attempting to read from a database where I have stored values. I am trying to add all of the values across each day, and have written the following code to do that. For some reason, only the first day's row is being summated. I'm sure that there is a reason that the condition of one of my loops isn't working, but I guess I am over-looking it. Any quick glances are appreciated.

$readsum =array();
$totalsum = 0;


for ($i=1; $i <= $numdays; $i++){
$readresult=mysql_query("SELECT * FROM `test`.`cost_table` WHERE `Day`='$i'",$LinkID);



while($rows=mysql_fetch_array($readresult)){
    $readsum[]=$rows['Yield'];
    $readsum[]=$rows['Rolls'];
    $readsum[]=$rows['Utilities'];
    $readsum[]=$rows['Payroll'];
    $readsum[]=$rows['Direct Materials'];
    $readsum[]=$rows['3rd Party'];
    $readsum[]=$rows['Supplies'];
    $readsum[]=$rows['Packaging'];
    $readsum[]=$rows['Rental'];
    $readsum[]=$rows['Other'];
}   

for($i=0; $i <= 9; $i++){
    $totalsum = $totalsum + $readsum[$i];
    }


echo $totalsum;
$totalsum = 0;

}

Right now, the output is only one value; the sum of the first row of the database. Being the 2nd day of the month, it should be calculating a second sum and echoing it as well.


Solution

  • To expand on my comment here is how I would rewrite the code to improve it:

    $readsum =array();
    $totalsum = 0;
    
    $readresult=mysql_query("SELECT * FROM `test`.`cost_table` ORDER BY `Day`",$LinkID);
    
    while($rows=mysql_fetch_array($readresult)){
        $readsum[$rows['Day']][]=$rows['Yield'];
        $readsum[$rows['Day']][]=$rows['Rolls'];
        $readsum[$rows['Day']][]=$rows['Utilities'];
        $readsum[$rows['Day']][]=$rows['Payroll'];
        $readsum[$rows['Day']][]=$rows['Direct Materials'];
        $readsum[$rows['Day']][]=$rows['3rd Party'];
        $readsum[$rows['Day']][]=$rows['Supplies'];
        $readsum[$rows['Day']][]=$rows['Packaging'];
        $readsum[$rows['Day']][]=$rows['Rental'];
        $readsum[$rows['Day']][]=$rows['Other'];
    }   
    
    //var_dump $readsum to see what you have to work with
    
    foreach($readsum as $day=>$dataArray){
      foreach($dataArray as $rsum){
        $totalsum = $totalsum + $rsum;
      }
      echo $totalsum;
      $totalsum = 0; 
    }
    

    Basically you do your query over the entire set.

    Go through the results to build up a nice easy to work with associative array.

    Then use that array to do whatever you want with the data.

    Much more reusable and easy to understand.