0

试图获取一个代码来显示我的帖子的类别,但我在显示每个类别的帖子数量时遇到了问题。

好吧,您在查看代码时明白了我的意思,现在每个类别都列出了类别总数...

开始了:

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

?>
4

1 回答 1

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
于 2012-09-03T19:39:38.113 回答