Jump to content

Multi-column Results


Recommended Posts

[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>&nbsp;</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

  • 5 months later...
  • 1 year later...
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

  • 1 year later...
this part of code[code=php:0]if($i < $max_columns)
{
    for($j=$i; $j<$max_columns;$j++)
        echo "<td>&nbsp;</td>";
}
?>
</tr>
</table>[/code]shold be[code=php:0]if($i > 0)
{
    for($j=$i; $j<$max_columns;$j++) echo "<td>&nbsp;</td>";
  echo '</tr>';
}
?>
</table>[/code]
Link to comment
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.