数据库查询与HTML整合

2024-04-09

通过以下步骤,您可以将数据库查询结果整合html 页面中:建立数据库连接。执行查询并存储结果。遍历查询结果并将其显示在 html 元素中。

使用 PHP 将数据库查询与 HTML 整合

整合数据库查询结果和 HTML 页面可使您创建动态和交互式 Web 应用程序。本文将引导您完成使用 PHP 执行此操作的步骤,并提供一个实战案例来说明该流程。

步骤 1:建立数据库连接

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// 创建连接
$conn = new <a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15713.html" target="_blank">mysql</a>i($servername, $username, $password, $dbname);

步骤 2:执行查询

要获取数据,请使用 mysqli_query() 函数执行查询。

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

步骤 3:获取查询结果

要遍历查询结果,请使用 mysqli_fetch_assoc() 函数。它会返回包含键值对的关联数组。

while ($row = $result->fetch_assoc()) {
    echo "{$row['id']}: {$row['name']}<br>";
}

实战案例:显示用户列表

以下示例展示了如何将用户列表从数据库查询到 HTML 表格中:

index.php

<!DOCTYPE html>
<html>
<head>
    <title>用户列表</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
            </tr>
        </thead>
        <tbody>
            <?php
            include 'db_connect.php';

            $sql = "SELECT * FROM users";
            $result = $conn->query($sql);

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td></tr>";
                }
            } else {
                echo "<tr><td co<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/79544.html" target="_blank">lsp</a>an='2'>没有用户</td></tr>";
            }
            ?>
        </tbody>
    </table>
</body>
</html>

db_connect.php

// 数据库连接信息
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

以上就是数据库查询与HTML整合的详细内容,更多请关注北冥有鱼其它相关技术文章!