Forum Moderators: coopster
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
if($i=='3'){echo"<tr>";}
if($i=='6'){echo"<tr>";}
etc
Thanks
Tom
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.
<?php
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>';
$column_count++;
if ($column_count >= $num_cols) {
// end the row, reset the colum counter.
// Next loop it will create a new row.
echo '</tr>';
$column_count=0;
}
}
// 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> </td>';
}
echo '</tr>';
}
echo '</table>';
?>
One of the modulus solutions [webmasterworld.com]