Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

From While Loop to valid table markup



8:29 am on Oct 1, 2009 (gmt 0)

5+ Year Member


I was wondering if there is a standard way to output data from while loop into valid table markup. The data can have a varying number of results.

At the moment I am using a counter to create a new row depending on the number of columns. The problem with this is determining when the data ends and finishing the table off properly. It also means a lot of conditionals which I guess isn't great for performance i.e somthing like




9:08 pm on Oct 1, 2009 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

It seems most people like to use the modulus operator to do this. But here's how I do it.

Basically a counter counts the columns. If it's 0, output <tr> - which is why it's at the top of the loop. When you reach the number of columns you want, at the end of the loop output a </tr>, reset counter to 0, which will output a new <tr> for the next row.

When the data's all done, if $count > 0 and less than number of columns, you output empty cells to fill out the last row.

include 'includes/dbconnect.php';
// Set the number of columns you want
$num_cols = 3;
$column_count = 0;
$select = 'select category from categories order by category'; //alphabetical if text
$result = mysql_query("$select");
echo '<table border="1" cellpadding="2" cellspacing="2">';
while($array = mysql_fetch_array($result)) {
if ($column_count==0) { echo '<tr>'; }
echo '<td><a href="yourscript.php?category=' . $array['category'] . '">' . $array['category']. '</a></td>';
if ($column_count >= $num_cols) {
// end the row, reset the colum counter.
// Next loop it will create a new row.
echo '</tr>';
// On the last row of data, it may not give you three full columns
// If $column_count is 0, it's good. Otherwise,
if (($column_count > 0) and ($column_count < $num_cols)) {
for ($i=$column_count;$i<$num_cols;$i++) {
echo '<td>&nbsp;</td>';
echo '</tr>';
echo '</table>';

One of the modulus solutions [webmasterworld.com]


11:16 am on Oct 2, 2009 (gmt 0)

5+ Year Member

Thanks a lot rocknbil that's working perfectly

Featured Threads

Hot Threads This Week

Hot Threads This Month