Link to home
Start Free TrialLog in
Avatar of MaybeItsJeremy
MaybeItsJeremy

asked on

MySQL query result, show only 5 results per line, after 5 are shown, start a new line.

How would I go about looping the results of a query to only show 5 results per line in my HTML? For example, There are 10 entries in the database table, I need to retrieve those, and then display 5 entries on each line of my template.... something like:

Row 1, Row 2, Row 3, Row 4, Row 5 (start a new line afterwards)
Row 6, Row 7, Row 8, Row 9, Row 10

How can I go about that? I know it's possible, I've seen it done numerous times. I'd also like to have a "default content" if the number of rows is not divesible by 5. Like if I had only 8 rows, I'd like to have a   to "take their place".
SOLUTION
Avatar of Batalf
Batalf
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<?php

echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($result)) {
 foreach($i=1; $i<=count($row); $i++) {
  echo "<td> $row[$i-1] </td>";
  if($i > 1 && $i%5==0) { echo "</tr><tr>"; }
 }
 for($i=1; $i <= $i%5; $i++) {
  echo "<td>&nbsp;</td>";
  $isNextTr = true;
 }
 if(isset($isNextTr)) { echo "</tr>"; }
}

?>
Typo.

<?php

echo "<table>";
echo "<tr>";

while($row = mysql_fetch_assoc($result)) {
 for($i=1; $i<=count($row); $i++) {
  echo "<td> $row[$i-1] </td>";
  if($i > 1 && $i%5==0) { echo "</tr><tr>"; }
 }
 for($i=1; $i <= $i%5; $i++) {
  echo "<td>&nbsp;</td>";
  $isNextTr = true;
 }
 if(isset($isNextTr) && $isNextTr == true) { echo "</tr>"; }
}

echo "</table>";
?>
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
(Sorry)^1000 and no more changes. (well, hopefully!)

Change the second "for" loop to this :

for($i=1; $i <= 5 - count($row)%5; $i++) {
  echo "<td>&nbsp;</td>";
  if($i == 5 - count($row)%5) { echo "</tr>"; }
 }
}
Avatar of MaybeItsJeremy
MaybeItsJeremy

ASKER

Thanks everyone... points split an evenly as possible...