首页 >后端开发 >php教程 >如何在 HTML 表中显示 MySQL 数据库值?

如何在 HTML 表中显示 MySQL 数据库值?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-28 13:33:10573浏览

How to Display MySQL Database Values in an HTML Table?

在网页上的 HTML 表中显示 MySQL 数据库值

要在 HTML 表中检索和显示数据库表中的值,请执行以下操作这些步骤:

获取数据:

  1. 使用 mysqli_connect 建立与数据库的连接。
  2. 使用 mysqli_query 执行查询以获取所需数据。
  3. 转换查询结果使用关联数组fetch_all.

示例:

$con = mysqli_connect("localhost", "peter", "abc123", "my_db");
$result = mysqli_query($con, "SELECT * FROM tickets LIMIT 50");
$data = $result->fetch_all(MYSQLI_ASSOC);

显示数据:

  1. 创建 HTML表并设置可见性的边框属性。
  2. 使用 PHP循环遍历 $data 数组,为每条记录创建表行和列。

示例:

<table border="1">
    <tr>
        <th>Submission ID</th>
        <th>Form ID</th>
        <th>IP</th>
        <th>Name</th>
        <th>E-mail</th>
        <th>Message</th>
    </tr>
    <?php foreach($data as $row): ?>
    <tr>
        <td><?= htmlspecialchars($row['submission_id']) ?></td>
        <td><?= htmlspecialchars($row['formID']) ?></td>
        <td><?= htmlspecialchars($row['IP']) ?></td>
        <td><?= htmlspecialchars($row['name']) ?></td>
        <td><?= htmlspecialchars($row['email']) ?></td>
        <td><?= htmlspecialchars($row['message']) ?></td>
    </tr>
    <?php endforeach ?>
</table>

此代码将生成 HTML表包含“tickets”表中的数据,并在相应的列中显示值。

以上是如何在 HTML 表中显示 MySQL 数据库值?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn