Displaying query results in columns

Although it easy fairly easy to pull results from your database and display them, often times you might want to display them in a crisp table format. The below script will help you display query results evenly through columns.

  1. <?php
  2. include 'config.php';
  3. include 'opendb.php';
  4. $table = 'your table here';
  5. $query  = "SELECT name FROM $table WHERE variable='$var' GROUP BY name"; //you can get rid of variable if not needed
  6. $result = mysql_query($query);
  7.  
  8. echo "&lt;table width=\"100%\"  border=\"0\" cellspacing=\"0\" cellpadding=\"0\"&gt;\n";
  9. $count = 0;
  10. $columns = 3; //column number declaration
  11. if(mysql_num_rows($result)) {
  12. while($myrow = mysql_fetch_array($result)) {
  13. // display list if there are records to display
  14. if($count == 0) echo "&lt;tr&gt;\n";
  15. printf("&lt;td&gt;&lt;a href=\"%s%s.html\"&gt;%s %s&lt;/a&gt;&lt;/td&gt;\n", $php_SELF, $myrow["name"], $myrow["name"], $myrow[""]);
  16. if($count == $columns - 1) echo "&lt;/tr&gt;\n";//here without the!
  17. $count = ++$count % $columns;
  18. }
  19. if($count!= 0) echo "&lt;/tr&gt;\n";
  20. echo "&lt;/table&gt;\n";
  21. } else {
  22. // no records to display
  23. echo "Sorry, no records were found!";
  24. }
  25. include 'closedb.php';
  26. ?>

Posted under Web Design

This post was written by Coyol on September 12, 2008

Tags: , ,