[英]Print Posts from all categories and their categories names
I try to achieve the following: 我尝试实现以下目标:
I display all posts from all categories and put the category name next to each post. 我显示所有类别的所有帖子,并将类别名称放在每个帖子旁边。 I do not understand where and why fail.
我不明白哪里失败,为什么失败。 All posts are multiplied by the number of categories.
所有帖子均乘以类别数。 Here is what I have till now:
这是我到目前为止所拥有的:
posts table:
post_id
post_title
post_content
category_id
categories table:
category_id
category_name
category_description
And my queries and PHP code: 还有我的查询和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);
And then: 接着:
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>";
}
}
I think this two foreaches part do things wrong. 我认为这两个foreach部分做错了事。 I can do one foreach to display all the posts but I do not know how to get their category names and put them next.
我可以做一个foreach来显示所有帖子,但是我不知道如何获取它们的类别名称并将其放在下一个位置。
That's the reason we have JOINS , 这就是我们拥有JOINS的原因,
SELECT * from posts p
LEFT JOIN categories c on c.id = p.category_id
And then you can simply need a single loop, 然后,您只需要一个循环,
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>";
}
select P.*, C.* from posts P
inner join categories C on C.category_id = P.category_id
You don't need 2 sql requests. 您不需要2个sql请求。 So you don't need 2 loops
因此您不需要2个循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.