Search code examples
phpsqlvariablesnested-loops

I cant pass variables between loops using PHP and SQL?


In the loops below, PHP doesn't seem to pass the outputted string back out to the loop that contains it for further manipulation, then making the output from this loop nothing at all.

Please help me understand why this is...

<?php

$finalTablePrint = '<html><body style="font-family:Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif; font-size:40px;">
                        LTU Activity Report<br/>
                        <span style="font-size:18px;">&nbsp;&nbsp;Date Created: ' . date("l jS \of F Y") . '<br/><br/>
                        <table width=100% style="background-color:white; font-size:12px; border-collapse:collapse;" >
                        <tr style="font-size:12px; font-weight:600; background-color:#d2dbdf; height:35px;">
                            <td>Activity</td><td>Department</td><td>Hours Spent</td><td>Month</td>
                        </tr>';

while ($row = mysql_fetch_assoc($result)) {
    $finalTablePrint .= '<tr><td colspan=4>' . $row['activity'] . '</td></tr>';
    while ($row_1 = mysql_fetch_assoc($result)) {
        if ($row_1['activity'] == $row['activity'] && $row_1['department'] == $row['department']) {
            $finalTablePrint .= '<tr style="height:30px;"><td colspan=3>' . $row['department'] . '</td>' . '<td>' . $row['hours'] . '</td><td>' . $row['month'] . '</td></tr>';
        }
    }
}

echo $finalTablePrint .='</table><script type="text/javascript">javascript:window.print(); setTimeout(\'window.location="../../admin/index.php"\',"1000");</script></body></html>';

Solution

  • Note that when you set off your second loop, you are calling the same SQL statement as the original one before it

      while ($row = mysql_fetch_assoc($result)) {   //1st while
    while ($row_1 = mysql_fetch_assoc($result)) {    //2nd while
    

    which in turn means that this if statement will allways be true....

     if ($row_1['activity'] == $row['activity'] && $row_1['department'] == $row['department']) { 
    

    and this will allways echo:

      $finalTablePrint .= '<tr style="height:30px;"><td colspan=3>'.$row['department'].'</td>'.'<td>'.$row['hours'].'</td><td>'.$row['month'].'</td></tr>';  
    

    so you should really remove your 2nd while/if statement... since it achieves nothing at the moment