Jump to content


Photo

Help Closing Table Row in a While Loop


  • Please log in to reply
3 replies to this topic

#1 thisagain

thisagain
  • New Members
  • Pip
  • Newbie
  • 8 posts

Posted 19 July 2006 - 06:55 PM

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.

 

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

 

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.



#2 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 19 July 2006 - 07:05 PM

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

<?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>';
?>

hth

#3 thisagain

thisagain
  • New Members
  • Pip
  • Newbie
  • 8 posts

Posted 19 July 2006 - 09:25 PM

Thanks akitchin!  I really appreciate the help.

Everything works except $empties gives me the wrong amount but I can figure that out.

#4 akitchin

akitchin
  • Staff Alumni
  • Advanced Member
  • 2,516 posts
  • LocationCalgary, AB, Canada

Posted 20 July 2006 - 05:40 AM

sorry, it should be:

$empties = $per_row - (--$i % $per_row);

since the $i represents the next cell number, not the one that has just executed.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users