homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

From While Loop to valid table markup

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


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)

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)

Thanks a lot rocknbil that's working perfectly

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved