Show Values from a MySQL Database Table Inside a HTML Table on a Webpage

Show values from a MySQL database table inside a HTML table on a webpage

Example taken from W3Schools: PHP Select Data from MySQL

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

It's a good place to learn from!

Dynamic table in HTML using MySQL and php

If you want to display the full contents of the database table as an HTML table, I suggest you make a function that will do all of this dynamically for you. This function should check that the table exists, fetch all the data, and fetch output HTML table with headers.

MySQLi solution

Here is my suggestion using MySQLi. First of all, you must make sure that the table actually exists. Then you can fetch all the data from the table. The object returned by mysqli::query() will have all metadata information about column names which you can use to display the header row. You can use fetch_fields() to iterate over each column metadata. The data can be fetched using fetch_all() method.

<?php

// create global connection using mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect("localhost", "username", "password", "database", "3306");
$mysqli->set_charset('utf8mb4'); // always set the charset

function outputMySQLToHTMLTable(mysqli $mysqli, string $table)
{
// Make sure that the table exists in the current database!
$tableNames = array_column($mysqli->query('SHOW TABLES')->fetch_all(), 0);
if (!in_array($table, $tableNames, true)) {
throw new UnexpectedValueException('Unknown table name provided!');
}
$res = $mysqli->query('SELECT * FROM '.$table);
$data = $res->fetch_all(MYSQLI_ASSOC);

echo '<table>';
// Display table header
echo '<thead>';
echo '<tr>';
foreach ($res->fetch_fields() as $column) {
echo '<th>'.htmlspecialchars($column->name).'</th>';
}
echo '</tr>';
echo '</thead>';
// If there is data then display each row
if ($data) {
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>'.htmlspecialchars($cell).'</td>';
}
echo '</tr>';
}
} else {
echo '<tr><td colspan="'.$res->field_count.'">No records in the table!</td></tr>';
}
echo '</table>';
}

outputMySQLToHTMLTable($mysqli, 'user');

PDO Solution

Using PDO is very similar but you have to pay attention to the differences in the APIs.

To get the table names, you can use fetchAll(PDO::FETCH_COLUMN) instead of array_column(). To get the column metadata, you need to use getColumnMeta() function.

<?php

$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'username', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);

function outputMySQLToHTMLTable(pdo $pdo, string $table)
{
// Make sure that the table exists in the current database!
$tableNames = $pdo->query('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN);
if (!in_array($table, $tableNames, true)) {
throw new UnexpectedValueException('Unknown table name provided!');
}
$stmt = $pdo->query('SELECT * FROM '.$table);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$columnCount = $stmt->columnCount();

echo '<table>';
// Display table header
echo '<thead>';
echo '<tr>';
for ($i = 0; $i < $columnCount; $i++) {
echo '<th>'.htmlspecialchars($stmt->getColumnMeta($i)['name']).'</th>';
}
echo '</tr>';
echo '</thead>';
// If there is data then display each row
if ($data) {
foreach ($data as $row) {
echo '<tr>';
foreach ($row as $cell) {
echo '<td>'.htmlspecialchars($cell).'</td>';
}
echo '</tr>';
}
} else {
echo '<tr><td colspan="'.$columnCount.'">No records in the table!</td></tr>';
}
echo '</table>';
}

outputMySQLToHTMLTable($pdo, 'user');

P.S. The table existence check can be optimized with the following code instead:

$tableNames = $pdo->prepare('SELECT COUNT(1) FROM information_schema.TABLES WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME=?');
$tableNames->execute([$table]);
if (!$tableNames->fetchColumn()) {
throw new UnexpectedValueException('Unknown table name provided!');
}

Display all MySQL table data in html table

You can do it if you are going to show all columns. Or, you can add your filters conditional.

However, as it seems you are new to web development, I make it in a simple way.

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>";

$i = 0;
while($row = $result->fetch_assoc())
{
if ($i == 0) {
$i++;
echo "<tr>";
foreach ($row as $key => $value) {
echo "<th>" . $key . "</th>";
}
echo "</tr>";
}
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

Extracting data from the database table and display in view

almost there!

{% for processed_outputs in outputs %}

has to be:

{% for outputs in processed_outputs %}
{{ outputs.major_cd }}
...
...

How do I display all tables in a database as HTML tables?

If you want to loop through all your tables and list the data from each one in a HTML table, including showing the column names, then this should work for you:

//get all the tables in the database
$sql = "SHOW TABLES FROM db_name";
$result = $connection->query($sql);

if ($result === false) die($conn->error);

//loop through the list of tables
while ($row = $result->fetch_row()) {
echo "<h2>Table: ".$row[0]."</h2>";

//now, for the current table, get all the data and loop through the rows
$sql2 = "SELECT * FROM ".$row[0];
$result2 = $connection->query($sql2);

if ($result2)
{
//get the column names
$fields = $result2->fetch_fields();
echo "<table><thead><tr>";

//loop through the field names and output each one as a column heading
foreach ($fields as $fld)
{
echo "<th>".$fld->name."</th>";
}
echo "</tr></thead><tbody>";

//get the rows
while ($row2 = $result2->fetch_row()) {
echo "<tr>";

//loop through each data value in the row and output into a HTML table cell
foreach ($row2 as $cell) {
echo "<td>".$cell."</td>";
}
echo "</tr>";
}

echo "</tbody></table><hr>";
}
else
{
echo "Problem retrieving data for ".$row[0].": ".$conn->error;
}
}


Related Topics



Leave a reply



Submit