OK I have an sql query that selects 8 items from a database. $result = mysql_query("select * from mytable WHERE active='yes' ORDER BY something DESC LIMIT 8) or exit(mysql_error()); Now I would normally just use a while loop and spit them all out in 1 big table while ($info = mysql_fetch_array($result)) { echo " <tr><td>$info['variable1'];</td></tr> <tr><td>$info['variable2'];</td></tr>"; } Or use a foreach loop, whichever I'm feeling that day. But in this case I want to list 4, then stop, end the table, start a new table, then list the other 4. How would you pull that off? I'm reading up on break / continue but I'm not getting it.
Simply do the math, initialize a counter variable and count it on the while loop. <? $counter = 1; while ($row = mysql_fetch_array($query)) { // Table 1 if ($counter == 1) echo "<table>\n" . " <tr>\n" . " <td>{$row['value']}</td>\n" . " </tr>\n"; elseif ($counter < 4) { echo " <tr>\n" . " <td>{$row['value']}</td>\n" . " </tr>\n"; } elseif ($counter == 4) { echo " <tr>\n" . " <td>{$row['value']}</td>\n" . " </tr>\n" . "</table>\n"; } // Table 2 elseif ($counter == 5) echo "<table>\n" . " <tr>\n" . " <td>{$row['value']}</td>\n" . " </tr>\n"; elseif ($counter < 8) { echo " <tr>\n" . " <td>{$row['value']}</td>\n" . " </tr>\n"; } elseif ($counter == 8) { echo " <tr>\n" . " <td>{$row['value']}</td>\n" . " </tr>\n" . "</table>\n"; } $counter++ } ?> PHP: If the actual query doesn't know how many results you are going to get, I would recommend looking into the modulas operator (%)
I would do: $counter = 1; while ($info = mysql_fetch_array($result)) { if ( $counter == 1 ) { echo '<table>'; } echo '<tr><td>' . $info['variable1'] . '</td></tr>'; echo '<tr><td>' . $info['variable4'] . '</td></tr>'; if ( $counter == 4 ) { echo '</table>'; } $counter++; if ( $counter > 4 ) { $counter = 1; } } Code (markup):
This should work...tested very little $Counter = 0; //Initialize Counter $RowsPerTable = 4; //Number of Rows per Table (Max) echo "<table border='1'>\n"; //Start Table while ($info = mysql_fetch_array($result)) { if(($Counter % $RowsPerTable == 0) && ($Counter != 0)) echo "</table>\n<table border='1'>\n"; echo "<tr><td>{$info['data']}</td></tr>\n"; $Counter++; } echo "</table>\n"; //End Table PHP: This should work no matter how many rows are returned or how many rows you want per table. I was having a problem getting an empty table to begin with because 0 % anything is always 0, so, I put a quick fix in there, couldn't think of any other way to do it (I'm having a brainfart). So, if you have anything better, please include it!