ober Posted June 9, 2006 Share Posted June 9, 2006 [b]Q:[/b] How do I create a multi-column layout for my gallery/store from MySQL results or an array?[b]A:[/b] A lot of times you'll see people suggest using CSS for layouts. This is one time 99% of developers are going to tell you to use a table.[code]<table cellspacing="3" cellpadding="3"><?php$query = "SELECT product FROM selling_items ORDER BY prod_id";$result = mysql_query($query) or die("There was a problem with the SQL query: " . mysql_error()); if($result && mysql_num_rows($result) > 0){ $i = 0; $max_columns = 3; while($row = mysql_fetch_array($result)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; // make sure we have a valid product if($product != "" && $product != null) echo "<td>$product</td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while} // end if results// clean up table - makes your code valid!if($i < $max_columns){ for($j=$i; $j<$max_columns;$j++) echo "<td> </td>";} ?></tr></table>[/code]To modify this for an array, just replace the while loop with a for loop and use your array as the input instead of the mysql fetch results. Link to comment Share on other sites More sharing options...
ober Posted November 10, 2006 Author Share Posted November 10, 2006 Updated 11/10/2006... contained a slight error with a call to "mssql_fetch_array()" instead of "mysql_fetch_array()". Link to comment Share on other sites More sharing options...
.josh Posted November 7, 2008 Share Posted November 7, 2008 A slight alternative to this is to use the modulus operator:example.php[code=php:0]<?php $cols = 0; echo "<table><tr>"; while ($cols < 20) { echo ($cols % 3 == 0)? "</tr><tr>" : ""; echo "<td>$cols</td>"; $cols++; } echo "</tr></table>";?> [/code] Link to comment Share on other sites More sharing options...
sasa Posted September 12, 2010 Share Posted September 12, 2010 this part of code[code=php:0]if($i < $max_columns){ for($j=$i; $j<$max_columns;$j++) echo "<td> </td>";} ?></tr></table>[/code]shold be[code=php:0]if($i > 0){ for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; echo '</tr>';} ?></table>[/code] Link to comment Share on other sites More sharing options...
Recommended Posts