Search code examples
phploopswhile-loopexecution

Output stops after php while loop


I have the following php code:

echo "<div style='float:left;'>";
echo "<table>";
echo "<tr>";
echo "<th></th>";
echo "<th colspan='4'>Laks beholdt</th>";
echo "</tr>";
echo "<tr>";
echo "<th>Uke</th>";
echo "<th>&lt;3 kg</th>";
echo "<th>3-7 kg</th>";
echo "<th>&gt;7 kg</th>";
echo "<th>Totalt</th>";
echo "</tr>";

while ($row = mysql_fetch_array($result, MYSQL_ASSOC) or die(mysql_error()))
{
   echo "<tr>";
   echo "<td>" . $row['Uke'] . "</td>";
   echo "<td style='text-align:right; padding-right:10px;'>" . number_format($row['SumSmall'], 1,
      ",", " ") . " kg</td>";
   echo "<td style='text-align:right; padding-right:10px;'>" . number_format($row['SumMedium'], 1,
      ",", " ") . " kg</td>";
   echo "<td style='text-align:right; padding-right:10px;'>" . number_format($row['SumLarge'], 1,
      ",", " ") . " kg</td>";
   echo "<td style='text-align:right; padding-right:10px;'>" . number_format($row['SumVekt'], 1, ",",
      " ") . " kg</td>";
   echo "</tr>";
}

echo "</table>";
echo "</div>";

I get the expected output from the while loop, but the end tags for my table and div -or any other output for that matter- does not show. I get no error message, and I fail to see any errors in my html. I've tried referencing the array by numbers instead of associative, but I get the same result.

I've written a hundred similar loops without error, but I'm out of ideas here :/


Solution

  • The or die() statement is causing it to stop execution. When $row = mysql_fetch_array($result, MYSQL_ASSOC) should be stopping the loop, it hits the die() instead. Since there was no error, nothing is printed from mysql_error()

    echo "Before loop\n";
    
    $x = 1;
    while($foo = bar($x) or die('Died')) {
        echo $x++, "\n";
    }
    
    echo "After loop\n";
    
    function bar($x) {
        if($x < 5) {
            return $x;
        }
        return false;
    }
    
    //outputs:
    //Before loop
    //1
    //2
    //3
    //4
    //Died
    

    Codepad version