MU_FAM
MU_FAM

Reputation: 79

How to count the number of comments for each article?

PHPMyAdmin Screenshot

I create a table the put the comments of each article so the comment_id is the auto increment for count the comments and article_id is the article ID from another table (foreign key).

I want to count the number of comments for each article and put it in new record or something just so I can show it in the article page like : "the number of comments : 5"

Upvotes: 0

Views: 80

Answers (3)

naiquevin
naiquevin

Reputation: 7796

You can use COUNT and GROUP BY for this

Try:

SELECT COUNT(*) as num_comments, article_id 
FROM comment_table 
GROUP BY article_id

Upvotes: 2

martincarlin87
martincarlin87

Reputation: 11042

I am just doing this from the top of my head so not sure if it will work:

// once you have connected to the database:
$query = "SELECT COUNT(article_id) FROM table_name WHERE article_id=1";
// you might want to have a variable set so that the article_id isn't hardcoded

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
echo "the number of comments: ". $row['COUNT(article_id)'] ."
}

Upvotes: 0

mellamokb
mellamokb

Reputation: 56769

  select article_id, count(article_id) as comment_count
    from comments
group by article_id
order by article_id

Upvotes: 3

Related Questions