Php-mysql Course

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('https://coursesweb.net', '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:
https://coursesweb.netmarplo.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'=>'https://coursesweb.net',
 'ro'=>'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 - https://coursesweb.netro - 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
1https://coursesweb.net890
2marplo.net1990
3www.php.net12890

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <a> tag for the address of the link?
src href rel
<a href="http://coursesweb.net/" title="CoursesWeb.net">CoursesWeb.net</a>
Which CSS property sets the type of the text font?
font-family text-decoration font-size
h2 {
  font-family:"Calibri",sans-serif;
}
What instruction selects all the <div> tags with class="cls"?
querySelector("div.cls") getElementsByTagName("div") querySelectorAll("div.cls")
var elm_list = document.querySelectorAll("div.cls");
var nr_elms = elm_list.length;       // number of selected items
alert(nr_elms);
Indicate the function that can be used to get the sum of values in an array.
array_sum() array_diff() array_shift()
$arr =[1, 2, 3, 4);
$arr_sum = array_sum($arr);
echo $arr_sum;       // 10
Display data from PHP Array, or MySQL in HTML table

Last accessed pages

  1. Get and Modify content of an Iframe (32494)
  2. The Mastery of Love (7690)
  3. Download HTM resources (90)
  4. HTML5 Quick Tutorial (5041)
  5. Styling HTML table with CSS (412)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (715)
  2. CSS cursor property - Custom Cursors (94)
  3. Read Excel file data in PHP - PhpExcelReader (71)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (67)
  5. PHP Unzipper - Extract Zip, Rar Archives (53)