如何按指定分类显示论坛帖子?代码仅展示首个分类帖子问题
问题分析与解决方案
问题根源
你的代码逻辑存在关键问题:mysqli_fetch_array($result_threads)会逐步消耗结果集指针,第一次遍历分类时,已经把$result_threads里的所有帖子取完,指针移到了结果集末尾。当循环到第二个分类时,mysqli_fetch_array再也取不到任何数据,所以第二个分类下无帖子显示。
解决方案一:提前缓存所有帖子数据
先把所有帖子一次性读取到数组中,之后每个分类循环时,遍历数组匹配对应分类的帖子:
// 先将所有帖子存入数组缓存 $all_threads = []; while($thread = mysqli_fetch_array($result_threads)) { $all_threads[] = $thread; } // 遍历分类并匹配对应帖子 while($category = mysqli_fetch_assoc($result_categories)){ echo "<div class='category'> <h4 class='cat-name'>".$category['name']."</h4> <div class='cat-threads'> <ul>"; // 遍历缓存的帖子数组,筛选当前分类的帖子 foreach($all_threads as $thread){ if($thread['category_id'] == $category['id']){ echo "<a href='showthread/?id=".$thread['id']."'><li>".$thread['title']."</li></a>"; } } echo "</ul> </div> </div>"; } ?>
解决方案二:使用SQL JOIN优化查询(推荐)
通过SQL的LEFT JOIN一次性关联分类和帖子表,按分类分组后输出,只需一次数据库查询,效率更高:
修改SQL查询语句:
SELECT c.id AS category_id, c.name AS category_name, t.id AS thread_id, t.title AS thread_title FROM categories c LEFT JOIN forum_threads t ON c.id = t.category_id ORDER BY c.id, t.id
修改PHP处理代码:
$current_category_id = null; while($row = mysqli_fetch_assoc($result)){ // 切换到新分类时,输出分类头部 if($row['category_id'] !== $current_category_id){ // 闭合上一个分类的标签(非首次循环) if($current_category_id !== null){ echo "</ul></div></div>"; } echo "<div class='category'> <h4 class='cat-name'>".$row['category_name']."</h4> <div class='cat-threads'> <ul>"; $current_category_id = $row['category_id']; } // 输出当前分类下的帖子(如果存在) if($row['thread_id'] !== null){ echo "<a href='showthread/?id=".$row['thread_id']."'><li>".$row['thread_title']."</li></a>"; } } // 闭合最后一个分类的标签 if($current_category_id !== null){ echo "</ul></div></div>"; } ?>
方案对比
- 方案一逻辑简单,适合数据量较小的场景,但需要额外的PHP循环筛选数据。
- 方案二通过SQL关联查询减少了数据库交互次数,性能更优,是生产环境的推荐写法。
内容的提问来源于stack exchange,提问作者Ognjenn Veselinovicc
相关产品推荐
相关产品推荐

