Skip to content Skip to sidebar Skip to footer

Printing A Record Multiple Times In PHP And MySql

I am trying to create a webpage that does a simple query of a table and displays the table to a page, but with one complex twist that has got me confused. Here are the column names

Solution 1:

You really should switch to PDO / mysqli, but with your current code it would be something like (for showers as in your example):

<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)):
  $count = 2 + $row["showers"];
  for ($i = 0; $i < $count)
  {
?> 
    <tr>
    <td><?php print $row["Date"];?></td> 
    <td><?php print $row["Inspector1"];?></td> 
    <td><?php print $row["Inspector2"];?></td>
    <td><?php print $row["Building_Name"];?></td>
    <td><?php print $row["Room"];?></td>
    <td><?php print ($i + 1);?></td>  
    </tr>
<?php
  }
endwhile;
?>

You probably want to change $row["shower_no"] to something like $i + 1 as that column does not appear in your database.


Solution 2:

If you have a variety of rules

I would handle this problem like this:

<?php 

function printRow($row=array(), $times=1) {
    for($i=0; $i<$times; $i++) {
        echo "
        <tr>
        <td>{$row["Date"]}</td> 
        <td>{$row["Inspector1"]}</td> 
        <td>{$row["Inspector2"]}</td>
        <td>{$row["Building_Name"]}</td>
        <td>{$row["Room"]}</td>
        <td>{$row["shower_no"]}</td>  
        </tr>
        ";
    }
}

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    switch(true) {
        case ($row['eyewashPlumbed']>0 or $row['EyewashBottles']>0):
            printRow($row, 3); // print 3 times
            break;
        case ($row['showers']==0): // print 2 times
            printRow($row, 2);
            break;
        default: // default print 1 time only
            printRow($row, 1);
    }
}
?>

Post a Comment for "Printing A Record Multiple Times In PHP And MySql"