Display data from PHP Array, or MySQL in HTML table

This tutorial shows you how to display data from PHP array, or MySQL database, into a HTML table.
To create a HTML table with data sored into an Array, first you must create the <table> tag, then use one of the loop instructions: FOR(), or FOREACH() to traverse the array elements, and add them into <td></td> tags. After the loop instruction, create the ending </table> tag.

Display data from numeric Array in HTML table

If the Array is a numeric array (with keys /index consecutive numbers), you can use the for() instruction to traverse the array.
- Explanations are in the comments in code.

<?php
// Numeric array with data that will be displayed in HTML table
$aray = array('http://coursesweb.net', 'www.marplo.net', 'Courses', 'Web Programming', 'PHP-MySQL');
$nr_elm = count($aray);        // gets number of elements in $aray

// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';
$nr_col = 2;       // Sets the number of columns

// If the array has elements
if ($nr_elm > 0) {
  // Traverse the array with FOR
  for($i=0; $i<$nr_elm; $i++) {
    $html_table .= '<td>' .$aray[$i]. '</td>';       // adds the value in column in table

    // If the number of columns is completed for a row (rest of division of ($i + 1) to $nr_col is 0)
    // Closes the current row, and begins another row
    $col_to_add = ($i+1) % $nr_col;
    if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
  }

  // Adds empty column if the current row is not completed
  if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col - $col_to_add). '">&nbsp;</td>';
}

$html_table .= '</tr></table>';         // ends the last row, and the table

// Delete posible empty row (<tr></tr>) which cand be created after last column
$html_table = str_replace('<tr></tr>', '', $html_table);

echo $html_table;        // display the HTML table
?>

- This code will display the following HTML table:
http://coursesweb.netwww.marplo.net
CoursesWeb Programming
PHP-MySQL 

Display data from associative Array in HTML table

If the Array is an associative array (each ID key is associated with a value), you can use the foreach() instruction to traverse the array.

<?php
// Associative array with data that will be displayed in HTML table
$aray = array(
 'en'=>'http://coursesweb.net',
 'ro'=>'www.marplo.net',
 'type'=>'Courses',
 8=>'PHP-MySQL'
);

// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1" cellspacing="0" cellpadding="2"><tr>';
$nr_col = 2;       // Sets the number of columns

$i = 0;       // index used to control when to add new row (incremented to each loop)
// Traverse the array with FOREACH
foreach($aray AS $key=>$val) {
  $html_table .= '<td>' .$key. ' - '. $val. '</td>';       // adds key-value in columns in table
  $i++;

  // If the number of columns is completed for a row (rest of division of $i to $nr_col is 0)
  // Closes the current row, and begins another row
  $col_to_add = $i % $nr_col;
  if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
}

// Adds empty column if the current row is not completed
if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col - $col_to_add). '">&nbsp;</td>';

$html_table .= '</tr></table>';         // ends the last row, and the table

// Delete posible empty row (<tr></tr>) which cand be created after last column
$html_table = str_replace('<tr></tr>', '', $html_table);

echo $html_table;        // display the HTML table
?>

- This code will display the following HTML table:
en - http://coursesweb.netro - www.marplo.net
type - Courses8 - PHP-MySQL

Create HTML table with data from MySQL database

The example below shows you how to create a HTML table with the columns and rows selected from a MySQL database, using PHP PDO.
The technique is the same, eaven if you use PDO or MySQLi to select data from database. First connect to database and perform the SQL query, then create a variable that contains the beginning of the HTML table, and the first row, with title for columns. Then, in the instruction that traverses the results set, to each loop add a row with selected columns in the HTML table. Add the </table> tag after the loop instruction.
- Example:
<?php
// Connection data (server_address, database, name, poassword)
$hostdb = 'localhost';
$namedb = 'tests';
$userdb = 'root';
$passdb = 'password';

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

  // Define and perform the SQL query
  $sql = "SELECT `id`, `site`, `visits` FROM `websites` WHERE `visits`>100";
  $result = $conn->query($sql);

  // If the SQL query is succesfully performed ($result not false)
  if($result !== false) {
    // Create the beginning of HTML table, and the first row with colums title
    $html_table = '<table border="1" cellspacing="0" cellpadding="2"><tr><th>ID</th><th>Site</th><th>Visits</th></tr>';

    // Parse the result set, and adds each row and colums in HTML table
    foreach($result as $row) {
      $html_table .= '<tr><td>' .$row['id']. '</td><td>' .$row['site']. '</td><td>' .$row['visits']. '</td></tr>';
    }
  }

  $conn = null;        // Disconnect

  $html_table .= '</table>';           // ends the HTML table

  echo $html_table;        // display the HTML table
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>

- This code can display a HTML table like this:
IDSiteVisits
1http://coursesweb.net890
2www.marplo.net1990
3www.php.net12890