Programming Tutorials

Retrieve multiple rows from mysql and automatically create a table in PHP

By: jhulbert in PHP Tutorials on 2011-07-09  

Quite often, you need to retrieve rows from a mysql table and display it on a PHP page. Every time, the number of columns and rows are different. So you can use this useful php code snippet that takes care of formulating the table automatically with the results obtained irrespective of the number of columns or rows.

<?php
$qry = "SELECT * FROM exp_member_data";
$res = mysql_query($mem_qry);

function mysql_fetch_all($res) {
   while($row=mysql_fetch_array($res)) {
       $return[] = $row;
   }
   return $return;
}

function create_table($dataArr) {
    echo "<tr>";
    for($j = 0; $j < count($dataArr); $j++) {
        echo "<td>".$dataArr[$j]."</td>";
    }
    echo "</tr>";
}

$all = mysql_fetch_all($res);

echo "<table class='data_table'>";

for($i = 0; $i < count($all); $i++) {
    create_table($all[$i]);
}

echo "</table>";

?>






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Latest Articles (in PHP)