Jump to content

Help Closing Table Row in a While Loop


thisagain

Recommended Posts

Hello.  I'm new to this forum and new to PHP so please forgive me for my amature code.

I am trying to generate a 4 column table that is filled with data from a database.  I have the following code which allows me to fill the table with one row and infinite columns (until I have no more data).  I want to close every row at 4 columns and start a new row and continue showing the data until I have no more data.

[hr]

<table>
<tr>

<?php
if($results){
while ($row = mysql_fetch_array($results)){
$key = $row["key"];
$name = $row["name"];
$photo = $row["photo"];
?>

  <!-- <?php echo($key); ?> -->
  <td>
  <a href="items.php?name=<?php echo("name"); ?>"><img src="<?php echo($photo); ?>" height="150" width="100"><br><?php echo($name); ?></a>
  </td>

<?php
}
}
?>

</tr>
</table>

[hr]

Am I using the wrong type of loop?  I haven't been able to put a count in the loop that actually increases every time it loops.  I hope someone can help me with this.  Would really appreciate it.

Link to comment
Share on other sites

you can do the following, although you may have to fine-tune:

[code]<?php
$per_row = 4;
$i  = 1;
while (stuff)
{
  // end the last row and start a new row if we're on a new set
  if (($i % $per_row) == 1 && $i > 1)
  {
    echo '</tr><tr>';
  }

  // echo a cell

  // increment the cell counter
  $i++;
}

// find the requisite number of empty cells
$empties = $per_row - ($i % $per_row);

// echo the empty cell and end the row
echo '<td colspan="'.$empties.'">&nbsp;</td></tr>';
?>[/code]

hth
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.