简体   繁体   English

列出每个类别的帖子数

[英]list numer of posts per category

Trying to get a code to display the categories of my posts and Im having an issue with presenting the number of posts per category. 试图获取代码以显示我的帖子类别,而Im在显示每个类别的帖子数量时遇到问题。

well, you get my point while looking in the code, now the total number of categories is listed on every category... 好吧,在查看代码时您已经明白了,现在每个类别上都列出了类别的总数...

here we go: 开始了:

<?php 
$listresult = mysql_query("SELECT distinct category FROM test_blog") 
or die(mysql_error());

$totalpostspercategory = mysql_num_rows($listresult); 

echo "<ul>";
  while($row = mysql_fetch_array( $listresult )) {

if (strlen($row['category']) > 45) {
    $row['category'] = substr($row['category'],0,45) . " ...";
} 

echo "<li><a href='index.php?category=" . $row['id'] . "'>" . $row['category'] ."</a> (" . $totalpostspercategory . ")</li>";
}
echo "</ul>";

?>

Assuming your table looks something like this . 假设您的桌子看起来像这样。 . .

create table your_table (
  blog_post_id integer not null,
  category varchar(35) not null,
  primary key (blog_post_id, category)
);

insert into your_table values (1, 'food');
insert into your_table values (1, 'recipes');
insert into your_table values (1, 'tofu');
insert into your_table values (2, 'food');
insert into your_table values (3, 'tofu');
insert into your_table values (3, 'vacation');

You can get the count directly using SQL by 您可以通过以下方式直接使用SQL获取计数:

select category, count(*) num_posts
from your_table
group by category
order by category;

category  count
--
food      2
recipes   1
tofu      2
vacation  1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM