[英]Count the number of posts within categories
I have a little problem. 我有一点问题。 I'm building a blog, and it is working.
我正在建立一个博客,它正在工作。 Now I want to add a menu with the categories.
现在,我想添加一个带有类别的菜单。 I have 2 tables in the same database
blog_posts
and blog_categories
. 我在同一数据库
blog_posts
和blog_categories
有2个表。 In the table blog_categories
, there are 2 rows: id and name. 在表格
blog_categories
,有2行:id和name。 Id is also in the blog_posts
table. ID也位于
blog_posts
表中。 The categories are displayed on the page, using a while loop. 使用while循环将类别显示在页面上。 But I want to display the number of posts that are in that categorie after the categorie name.
但是我想在类别名称之后显示该类别中的帖子数。
It would look like this: 它看起来像这样:
Cat1: 1 类别1:
Cat2: 4 第2类:4
Cat3: 2 第3类:2
How can I do this? 我怎样才能做到这一点?
Tables: 表格:
blog_posts(id, title, catid, .... )
blog_categories(id, title, ... )
PDO: PDO:
$sql=$dbh->query("SELECT blog_categories.*, COUNT(blog_posts.CatID) AS count FROM blog_categories LEFT JOIN blog_posts ON blog_posts.CatID=blog_categories.ID GROUP BY blog_categories.ID ORDER BY count DESC");
while($row=$sql->fetch(PDO::FETCH_OBJ)) {
echo $row->title.':'.$count;
}
Result: 结果:
Cat 2: 5
Cat 1: 3
Cat 3: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.