列出每个类别的帖子数量

时间:2012-09-03 19:30:17

标签: php

尝试获取代码以显示我的帖子类别,而且我在提出每个类别的帖子数量方面存在问题。

嗯,你在查看代码时得到我的观点,现在每个类别都列出了类别的总数......

我们走了:

<?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>";

?>

1 个答案:

答案 0 :(得分:1)

假设你的表看起来像这样。 。

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');

您可以通过

直接使用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
相关问题