You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从SQL表获取数据并每3条记录生成新表格行

实现每3条记录一行的表格布局

下面是修改后的完整代码,直接实现你需要的每3条记录自动换行的表格布局:

<style type="text/css">
table {
  border: 1px solid #1C6EA4;
  background-color: #EEEEEE;
  text-align: center;
  border-collapse: collapse;
}
td {
  width: 33%;
  border: 1px solid #1C6EA4; /* 可选:添加td边框让结构更清晰 */
}
</style>

<table>
<?php
include "db.php";

// 单次数据库连接,避免重复创建连接消耗资源
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

$select = "SELECT * FROM equipment";
$resultselect = $connection->query($select);

$index = 0;
while ($row = $resultselect->fetch_assoc()) {
    $index++;
    // 每3条记录的起始位置(第1、4、7...条)开启新行
    if ($index % 3 == 1) {
        echo "\n<tr>";
    }
    
    echo "\n    <td>" . $row["Equipment_Name"] . "</td>";
    
    // 每3条记录的结束位置(第3、6、9...条)闭合当前行
    if ($index % 3 == 0) {
        echo "\n</tr>";
    }
}

// 处理总记录数不是3的倍数的情况,确保最后一行被正确闭合
if ($index % 3 != 0) {
    echo "\n</tr>";
}

$connection->close();
?>
</table>

关键修改说明

  1. 合并数据库连接:原代码创建了两次数据库连接,现在简化为单次连接,减少不必要的资源消耗。
  2. 添加循环计数器:用$index变量跟踪当前处理的记录序号,以此控制表格行的生成时机。
  3. 行结构控制:
    • 当记录序号为1、4、7...时(即$index % 3 == 1),输出<tr>开启新行。
    • 当记录序号为3、6、9...时(即$index % 3 == 0),输出</tr>闭合当前行。
  4. 补全最后一行:如果总记录数不是3的倍数(比如7条记录),循环结束后手动闭合未完成的<tr>,保证HTML结构合法。

内容的提问来源于stack exchange,提问作者Chris Reilly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 13:22:51