3

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?

2
  • where do you close the first tr that you open? The one near the table declaration. Commented Jan 2, 2011 at 16:35
  • Sorry missed that bit of code, added now. Commented Jan 2, 2011 at 16:37

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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.

Comments

0

Or with modulo:


    if ($i % 3 == 0) {
      echo '</tr><tr>';
    } 

so you wouldnt have to reset the $i.

Comments

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

should read:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.