PHP+SQL从本地服务器读取数据到HTML表格的显示问题
数据库数据展示到HTML表格的问题修正方案
问题根源
- 仅显示一行数据:未通过循环遍历查询结果集,只执行了一次数据获取操作
- 所有结果挤在同一行:HTML表格的
<tr>标签仅在循环外定义了一次,循环内只输出<td>,导致所有单元格都属于同一行
代码修正方案
1. 修复SQL注入风险与PHP查询逻辑
原PHP代码直接拼接用户输入到SQL语句,存在严重的SQL注入风险,同时确保查询结果集正确传递:
<?php if (isset($_POST["submit"])) { session_start(); include_once 'includes/dbh.inc.php'; // 使用预处理语句避免SQL注入 $sql = "SELECT * FROM products WHERE ProductPLU = ? OR ProductEAN = ? OR ProductIC = ?"; $stmt = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt, "sss", $_POST["productPLU"], $_POST["productEAN"], $_POST["productIC"]); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); } ?>
2. 修复HTML表格行结构
将<tr>标签移入while循环,确保每一条数据库记录对应表格的一行:
<div class="centred-container table"> <table class="table-results"> <tr class="tr-table"> <th class="th-table th-univ">Product name</th> <th class="th-table th-univ">Cod PLU</th> <th class="th-table th-univ">Cod Intern</th> <th class="th-table th-univ">Cod EAN/Bare</th> <th class="th-table th-univ">Unitate</th> <th class="th-table th-univ">Pret</th> <th class="th-table th-univ">Stoc</th> </tr> <?php // 确保$result存在且有数据时再循环 if (isset($result) && mysqli_num_rows($result) > 0) { while ($row = mysqli_fetch_assoc($result)) { ?> <tr class="tr-table"> <td><?php echo htmlspecialchars($row["ProductName"]); ?></td> <td><?php echo htmlspecialchars($row["ProductPLU"]); ?></td> <td><?php echo htmlspecialchars($row["ProductIC"]); ?></td> <td><?php echo htmlspecialchars($row["ProductEAN"]); ?></td> <td><?php echo htmlspecialchars($row["ProductUnit"]); ?></td> <td><?php echo htmlspecialchars($row["ProductPrice"]); ?></td> <td><?php echo htmlspecialchars($row["ProductStock"]); ?></td> </tr> <?php } } else { // 无数据时提示 echo "<tr><td colspan='7'>暂无匹配数据</td></tr>"; } ?> </table> </div>
额外优化说明
- 使用
htmlspecialchars()转义输出内容,防止XSS攻击 - 添加无数据时的提示信息,提升用户体验
- 采用预处理语句彻底解决SQL注入问题,这是生产环境必须的安全措施
内容的提问来源于stack exchange,提问作者AnoDev DevJunior
相关产品推荐
相关产品推荐

