我尝试实现以下目标:
我显示所有类别的所有帖子,并在每个帖子旁边放置类别名称。 我不明白失败的地点和原因。所有帖子都乘以类别数量。 这就是我现在所拥有的:
posts table:
post_id
post_title
post_content
category_id
categories table:
category_id
category_name
category_description
我的查询和PHP代码:
// I select all categories with their id and name
$stmt = $db->prepare("SELECT * FROM categories");
$stmt->execute();
$row_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
// I select all posts too
$stmt = $db->prepare("SELECT * FROM posts");
$stmt->execute();
$row_posts_all = $stmt->fetchAll(PDO::FETCH_ASSOC);
然后:
foreach ($row_posts_all as $array_index_number => $name_of_index) {
foreach ($row_categories as $array_index_number_categories => $name_of_index_category) {
print $name_of_index['post_title'] . " posted in: " . $name_of_index_category['category_name'] . "<br><br>";
}
}
我认为这两个前言部分做错了。我可以做一个foreach来显示所有帖子,但我不知道如何获取他们的类别名称并将它们放在下一个。
答案 0 :(得分:1)
这就是我们 JOINS ,
的原因SELECT * from posts p
LEFT JOIN categories c on c.id = p.category_id
然后你只需要一个循环,
foreach ($row_posts_all as $array_index_number => $name_of_index) {
echo $name_of_index['post_title'] . " posted in: " . $name_of_index['category_name'] . "<br><br>";
}
答案 1 :(得分:0)
select P.*, C.* from posts P
inner join categories C on C.category_id = P.category_id
您不需要2个sql请求。所以你不需要2个循环