<?php
// Create a MySQLi connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
function outputMySQLToHTMLTable(mysqli $mysqli, string $table)
{
// Check table existence
$tableNames = array_column($mysqli->query('SHOW TABLES')->fetch_all(), 0);
if (!in_array($table, $tableNames, true)) {
throw new UnexpectedValueException('Unknown table name provided!');
}
// Fetch data and metadata
$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>';
// Display table rows
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>';
}
// Output the table
outputMySQLToHTMLTable($mysqli, 'user');
Copy after login
The PDO approach is similar, but you'll need to use fetchAll(PDO::FETCH_COLUMN) for table name validation and getColumnMeta() for column metadata.
This approach ensures that your code can dynamically generate HTML tables based on the latest table structure in MySQL, eliminating the need for manual header updates.
The above is the detailed content of How Can I Dynamically Generate HTML Tables from MySQL Data Without Manually Specifying Headers?. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn