【问题标题】:Dynamic table in HTML using MySQL and php使用 MySQL 和 php 的 HTML 中的动态表
【发布时间】:2020-10-10 13:24:48
【问题描述】:

我看过很多关于如何使用 PHP 和 Mysql 在 HTML 中构建表格的帖子,但我的问题是,我经常更改 MySQL 列的标题。有什么办法可以让 PHP 自动更新代码,这样我就可以输入表格名称并打印表格,而无需我必须输入所有标签?

<?php

$table = "user";
$database = "database";
$conn = mysqli_connect("localhost", "username", "password", "database", "3306");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM $table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<tr><td>" . $row["id"] . "</td><td>" . $row["first_name"] . "</td><td>" . $row["last_name"] . "</td><td>" . $row["birthday"] . "</td></tr>";
    }
    echo "</table>";
} else {
    echo "0 result";
}

$conn->close();

【问题讨论】:

标签: php html mysql


【解决方案1】:

如果您想将数据库表的全部内容显示为 HTML 表,我建议您创建一个函数来为您动态完成所有这些工作。此函数应检查表是否存在,获取所有数据,并获取带有标题的输出 HTML 表。

MySQLi 解决方案

这是我使用 MySQLi 的建议。首先,您必须确保该表确实存在。然后您可以从表中获取所有数据。 mysqli::query() 返回的对象将包含有关列名的所有元数据信息,您可以使用这些信息显示标题行。您可以使用fetch_fields() 来遍历每列元数据。可以使用fetch_all()方法获取数据。

<?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 解决方案

使用 PDO 非常相似,但您必须注意 API 的差异。

要获取表名,您可以使用fetchAll(PDO::FETCH_COLUMN) 而不是array_column()。获取列元数据需要使用getColumnMeta()函数。

<?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.可以改用以下代码优化表存在性检查:

$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!');
}

【讨论】:

    【解决方案2】:

    我刚刚阅读了您的问题,并进行了编码以满足您的需求,但是我使用了 PDO 而不是 MYSQLI,也许您最好理解代码,因为使用 PDO 一切都更简单。而我做的方式,你不需要把所有的标签都放,PHP会自动更新,并且知道文件必须以扩展名.php结尾!

    <?php
    
    $conn = new PDO("mysql:host=localhost;dbname=YOUR_DATABASE_HERE", "USERNAME", "PASSWORD");
    
    
    if(!$conn){
        echo "Could not connect!";
    }          
    
    ?>
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            table, th, td {
                border: 1px solid black;
            }
        </style>
    </head>
    <body>
        <table style="width:100%;">
            <thead>
            <tr>
                <th>ID</th>
                <th>FirstName</th>
                <th>LastName</th>
                <th>Birthday</th>
                </tr>
            </thead>
            <tbody>
            <?php
            
            $sql = "SELECT * FROM user";
            $result = $conn->prepare($sql);
            $result->execute();
    
            if($result->rowCount() > 0):
                $rows = $result->fetchAll();
                foreach($rows as $row):
            ?>
            <tr>
                <td><?php echo $row['id'];  ?></td>
                <td><?php echo $row['first_name']; ?></td>
                <td><?php echo $row['last_name']; ?></td>
                <td><?php echo $row['birthday']; ?></td>
            </tr>
            </tbody>
    
            <?php
            endforeach;
        endif;
            ?>
        </table>
    </body>
    </html>
    

    【讨论】:

    • 请不要混合使用 PHP 和 HTML。这很快就会变得一团糟。将 PHP 分开,然后只显示 HTML 中的值。
    • if($result-&gt;rowCount() &gt; 0):的目的是什么?
    • 为什么是if(!$conn){?为什么没有切换错误报告?
    • 我看不出这是如何回答这个问题的。您仍然有硬编码的列名。
    • 我回答的目的是为了让一切变得更简单,使用 PHP 编写 HTML 代码可能会让人难以理解代码,尤其是对于一个不太懂行的人来说,所以值得说把 HTML 和 PHP 分开可以让最简单的代码更容易理解。不,我没有更改错误报告,这取决于用户为用户,我相信该人必须知道他们正在通知的数据才能建立连接,否则将无法建立连接。跨度>
    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多