PDO使用fetchAll、fetch及循环仅返回1行 下拉菜单实现求助
问题解决方案
错误原因
- PHP循环逻辑错误:你在
foreach遍历查询结果时,每次都给$categ变量重新赋值,循环结束后该变量只会保留最后一行的cat_slug值,之前的所有结果都被覆盖。 - 前端模板逻辑错误:你仅编写了单个
<li>标签,没有遍历所有查询到的分类条目,自然只能展示一条数据。 - 额外注意:你编写的SQL语句中
`cat_slug`和FROM之间缺少空格,可能触发SQL语法错误,需要补上。
修改后的PHP代码
$acces = 'Electronics'; $categoryList = []; // 初始化数组存储所有匹配的分类 $conn = $pdo->open(); try{ // 补全cat_slug和FROM之间的空格 $stmt = $conn->prepare("SELECT `id`, `cat_slug` FROM mall_category WHERE name = :acces"); $stmt->execute(['acces' => $acces]); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $row) { $categoryList[] = $row; // 将每一行分类数据追加到数组中 } } catch(PDOException $e){ echo "连接出错: " . $e->getMessage(); } $pdo->close();
修改后的前端代码
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Electronics</a> <ul class="dropdown"> <!-- 遍历分类数组输出所有条目 --> <?php foreach($categoryList as $item): ?> <li><a href='shopping.php?category=<?php echo $item['cat_slug']?>'><?php echo $item['cat_slug']; ?></a></li> <?php endforeach; ?> </ul> </li>
内容的提问来源于stack exchange,提问作者the_guru
相关产品推荐
相关产品推荐

