Output MySQL data in columns

If you’re going to display a huge number of data from MySQL, a one column list might not be the optimal solution. In some cases,  a 2 or 3 column list makes it easier for the user to navigate in the result, and makes the page shorter.

In this guide you will learn how to make a simple php script that can output data into nicely formatted columns.

The basic idea behind the script is, that it takes a MySQL array and displays it in a table with a customizable amount of columns. The HTML is W3C compliant.

The script in this post can be customized in many ways. The most important parameter to notice is the:

$cols=2;

The number 2 means that the script will output the data in 2 columns. However you can change the number of cols from 2 to whatever number you like. This is a example of a 3 columns output:

The script itself looks like this:

<?
$res = mysql_query(“[insert your mysql query here]”);
$rows = mysql_num_rows($res);
$counter = 1;
$cols = 2;
echo (“<table>\n”);
for($i = 0; $i < $rows/$cols; $i++) {
echo (“<tr>”);
for($j=0; $j < $cols && $counter <= $rows ;$j++, $counter++) {
echo (“<td>[insert the data you want to display here]</td>\n”);
}
echo (“</tr>\n”);
}
echo (“</table>\n”);
?>

You only need to insert your own MySQL query, and what data you want to display, and then you’re up and running.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

Comments are closed.