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
https://forums.phpfreaks.com/topic/15067-help-closing-table-row-in-a-while-loop/
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

Archived

This topic is now archived and is closed to further replies.

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