Dynamic table in HTML using MySQL and php

前端 未结 2 875
挽巷
挽巷 2021-01-23 15:32

I\'ve seen many posts about how to build a table in HTML with PHP and Mysql, but my problem is, that I often change the headers of MySQL columns. Is there any way that PHP autom

2条回答
  •  不知归路
    2021-01-23 16:01

    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.

    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 '';
        // Display table header
        echo '';
        echo '';
        foreach ($res->fetch_fields() as $column) {
            echo '';
        }
        echo '';
        echo '';
        // If there is data then display each row
        if ($data) {
            foreach ($data as $row) {
                echo '';
                foreach ($row as $cell) {
                    echo '';
                }
                echo '';
            }
        } else {
            echo '';
        }
        echo '
    '.htmlspecialchars($column->name).'
    '.htmlspecialchars($cell).'
    No records in the 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.

     \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 '';
        // Display table header
        echo '';
        echo '';
        for ($i = 0; $i < $columnCount; $i++) {
            echo '';
        }
        echo '';
        echo '';
        // If there is data then display each row
        if ($data) {
            foreach ($data as $row) {
                echo '';
                foreach ($row as $cell) {
                    echo '';
                }
                echo '';
            }
        } else {
            echo '';
        }
        echo '
    '.htmlspecialchars($stmt->getColumnMeta($i)['name']).'
    '.htmlspecialchars($cell).'
    No records in the 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!');
    }
    

提交回复
热议问题