Display Records In Multiple Coulmns

by Hiroshi on September 27, 2008

in Scripts, Useful Scripts

We can display data fetched from database in a variety of ways. Depends upon our requirement. By multiple columns I mean dividing all fetches data into columns and displaying it. Here is how We can divide the resultset into multiple columns.

Spliting Data into 3 Columns

<?php
// Selecting Data From Database
$sql="select * from tableName order by id desc";
if(mysql_query($sql))
{
$check=mysql_query($sql);
//total number of records set in database
$no=mysql_num_rows($check);
}
?>
<?php
// start loop
for($i=0; $i<$no; $i++)
{
// Here and at the bottom where loop finishes 3 is the value which will split the fetched data into three columns
if($i%3==0){echo"<tr><td>";}else{echo "<td>";
}
?>
<?php
// Display data fetched
print mysql_result($check,0+$i,"name"); 
?>
<?php
if($i%3==0){echo "</td>";}else{echo "</td>";
}
}
echo "</tr>";
?>

By changing value 3 which is at the beginning and end of loop, you should be able to split the fetched data in multiple columns as required. Although the above example can serve the purpose of displaying data into many columns as you want but I would like to share another example which is for 2 columns.

Spliting data into Two Columns – Second Way

<?php
//it tells the data what collumn to go to
$count = 1;
$column = 1;
$result=mysql_query ("select * from tabbeName ORDER by id");
//loop statement
while ($myrow = mysql_fetch_array ($result))
{
// this is the column 1
if ($column == 1)
{
printf("<tr><td width='320px' class='onebrd2cover'><font color='#999999'>$count.</font> <a href='pageName.php?mid=$myrow[catid]'>%s</a></td>",$myrow[catname]);
}
else{
//this  is the column 2
printf("<td width='320px' class='onebrd2'><font color='#999999'>$count.</font> <a href='pageName.php?mid=$myrow[catid]'>%s</a></td></tr>",$myrow[catname]);
}
//increment the count
$count += 1;
// this is a modulus operator it gets the remainder of the equation
$column = $count % 2;
}
?>

Related Posts

Previous post:

Next post: