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 )

Convert XML to CSV in PHP

for Loops in PHP

PHP file upload (Large Files)

PHP file upload prompts authentication for anonymous users

isset() function in PHP

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform


PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Function to return number of digits of an integer in PHP

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/ into server:

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Malware: global $ob_starting;

Latest Articles (in PHP)

Comment on this tutorial