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

By: jhulbert  

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.

$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++) {

echo "</table>";


Archived Comments

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial