如何用PHP+PDO将MySQL查询结果转为多列HTML表格(带图片名称)
问题解决步骤
1. 修复PDO数据获取问题
你的代码中setFetchMode仅设置数据获取模式但不返回实际结果,需替换为fetchAll来获取完整的查询结果集:
if (isset($_GET['color']) && isset($_GET['altmode'])) { $stmt = $conn->prepare("SELECT id,name,image1 FROM transformers WHERE color=:color AND altmode=:altmode"); $stmt->bindParam(':color', $_GET['color']); $stmt->bindParam(':altmode', $_GET['altmode']); $stmt->execute(); // 将查询结果转为关联数组 $transformers = $stmt->fetchAll(PDO::FETCH_ASSOC); // 处理无匹配结果的情况 if (empty($transformers)) { echo "<p>No matching Transformers found.</p>"; } else { // 调用渲染函数生成表格 renderTransformerTable($transformers); } } else { echo "<p id=\"error\">You didn't search for anything! Go to <a href=\"index.php\">the main page</a> to find a figure!</p>"; }
2. 实现多列表格渲染
创建专用函数生成2-3列布局的表格,每个单元格包含图片及下方名称:
function renderTransformerTable($items) { $columns = 3; // 可修改为2切换双列布局 $totalItems = count($items); echo '<table style="width:100%; border-collapse: separate; border-spacing: 15px;">'; $counter = 0; foreach ($items as $item) { // 每$columns个单元格开启新行 if ($counter % $columns === 0) { echo '<tr>'; } // 转义输出防止XSS攻击 $name = htmlspecialchars($item['name']); $imageUrl = htmlspecialchars($item['image1']); echo '<td style="text-align:center; vertical-align:top; width:' . (100/$columns) . '%;">'; echo '<img src="' . $imageUrl . '" alt="' . $name . '" style="max-width:100%; height:auto; margin-bottom:8px;">'; echo '<br><strong>' . $name . '</strong>'; echo '</td>'; // 每$columns个单元格闭合当前行 if ($counter % $columns === $columns - 1) { echo '</tr>'; } $counter++; } // 补全最后一行的空单元格(保证表格结构完整) while ($counter % $columns !== 0) { echo '<td></td>'; $counter++; } if ($counter % $columns === 0) { echo '</tr>'; } echo '</table>'; }
核心细节说明
- 安全防护:使用
htmlspecialchars()转义所有数据库输出内容,避免跨站脚本攻击。 - 布局灵活性:修改
$columns变量可快速切换2列或3列布局。 - 样式优化:内嵌CSS确保单元格宽度均匀、内容居中,图片自适应容器宽度。
- 异常处理:新增无匹配结果时的提示,提升用户体验。
内容的提问来源于stack exchange,提问作者Krisha
相关产品推荐
相关产品推荐

