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>";


Most Viewed Articles (in PHP )

Function to sort array by elements and count of element in PHP

Resume or Pause File Uploads in PHP

preg_match(), function preg_match_all(), preg_grep() in PHP

Count occurrences of a character in a String in PHP

Exception in module wampmanager.exe at 000F15A0 in Windows 8

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

Installing PHP and MySQL in windows, mac and linux


PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

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:

Function to convert strings to strict booleans in PHP

PHP pages does not display in IIS 6 with Windows 2003

Malware: global $ob_starting;

Latest Articles (in PHP)

Comment on this tutorial