All about PHP/MySQL

Thursday, March 13, 2008

Create nested (dynamic) table

In a project where i was calling the data from a mysql table, the requirement came to place it in a html table with a specific number of columns in it. Code should break the row after 3 columns (for example) and a new row of table should start after that. I wrote the following function to accomplish this task. I hope you will find it useful for your scripts.

<?php
function DrawTable($data,$total,$col)
{
$end = '0';
$newrowcount = '0';
?>
<table border="1" cellspacing="1" width="100%" id="AutoNumber1">
<?php while ($row = mysql_fetch_array($data)){
if ($newrowcount == $col)
{
$newrowcount = 0;
echo "<tr>";
}
?>

<td><?php echo $row['Name']; ?></td>
<?php $newrowcount++;
if ($newrowcount == $col) {echo"</tr>";}

$end = $end + 1;
} ?>
</table>
<?php
return true;
}
?>

Usage:
In my example, I have a table named as 'country' having the countries of world. I will display them in html table with a sequence of 3 columns in a row. Lets start the code.

<?php
include "db.php";
$result = mysql_query("select * from country order by Name") or die(mysql_error());
$total = mysql_num_rows($result);
DrawTable($result,$total,3);
?>

As you noticed, I included the db file, executed the query and got its result and the total number of records it has. Then i passed the three arguments to the function. First is the record set, second is the total number of records and the third is the number of columns I want to create in a single row. Then I displayed the country name in the function among the <td> and </td> tags. You can do your own experiments up there as this is just one example of how it can be. And of course you can easily format the html table according to your specific page layout. Possibilities are endless.

If you have any question or want explanation then kindly post the comment and I will try to reply in minimum time.

Thanks

Happy Coding :-)

1 Comments:

  • Chers, just what I was looking for. I have some issues now with re-declaring the function on the second time round, although I am well on my way to solving my dynamic table problem, Thanks!

    By Blogger , At May 30, 2008 at 6:00 AM  

Post a Comment

Subscribe to Post Comments [Atom]



Links to this post:

Create a Link

<< Home