Reputation:
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
. In the table blog_categories
, there are 2 rows: id and name. Id is also in the blog_posts
table. The categories are displayed on the page, using a while loop. 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
Cat2: 4
Cat3: 2
How can I do this?
Upvotes: 0
Views: 492
Reputation: 35
Tables:
blog_posts(id, title, catid, .... )
blog_categories(id, title, ... )
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
Upvotes: 1