Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP while loop, table row

I'm trying to loop through a database and output data into a div, if there are 3 divs horizontally across it will the start a new tr until it reaches another 3 etc. It is currently outputted like :

[] [] []
[]
[] []

Currently I have it working when it reaches 3 it starts a new row, but I don't know how I can only echo a new tr once? As it creates a new table row each time.

echo '<table><tr>';  

while ($result) 
{
    $i ++;
    if ($i&3)
    {
      echo '<td>
         <div>Row Data</div>
       </td>'; 
    }

    else
    {       
      echo '<tr>
        <td>
          <div>Row Data</div>
        </td></tr>';
   }
}  
echo '</tr></table>';

The $result variable is the recordset from my SQL query, everything works fine I just don't know how to only create a new table row once?

like image 505
Elliott Avatar asked Nov 28 '25 21:11

Elliott


1 Answers

you need to reset your $i variable to 1 when you hit 3...

$i = 0;
echo '<table><tr>';  

while ($result) 
{

    if ($i<=2)
    {
      echo '<td>
         <div>Row Data</div>
       </td>'; 
    }

    else
    {       
      echo '</tr><tr>';
      echo '<td><div>Row Data</div></td>'; 
      $i = 0;
   }
    $i ++;

}  
echo '</tr></table>';

Or something like this...

like image 196
webdad3 Avatar answered Dec 01 '25 12:12

webdad3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!