PHP while loop, table row

16,730

Solution 1

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...

Solution 2

echo '<table><tr>';
$i = 0;
while ($result) {
   if ($i > 2) {
      echo '</tr><tr>';
      $i = 0;
   }
   echo '<td></td>';
   $i++;
}
echo '</tr></table>';

Solution 3

I think you have a slightly slip of logic in your code. You want to break the line when 3 <td> have been added. currently you add a <td> in any case. Your counting is not working anymore.

Also I don't think bitwise operation is what you want. If you want 3 td's all the time, you will not accomplish that with &3. for example 3$3 is true, but 6&3 is not true. 7&3 is true. 11&3 is true. then 15&3 is true. You can either reset $i or you can use the % operator.

Share:
16,730
Elliott
Author by

Elliott

Web Engineer @ 10up. WordPress fan boy.

Updated on June 27, 2022

Comments

  • Elliott
    Elliott almost 2 years

    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?