簡體   English   中英

列出每個類別的帖子數

[英]list numer of posts per category

試圖獲取代碼以顯示我的帖子類別,而Im在顯示每個類別的帖子數量時遇到問題。

好吧,在查看代碼時您已經明白了,現在每個類別上都列出了類別的總數...

開始了:

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

?>

假設您的桌子看起來像這樣。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM