简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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