S
S
sugarufc2015-07-10 13:23:53
PHP
sugarufc, 2015-07-10 13:23:53

How to display the number of comments on an article?

There are two tables in the database.
1st table with articles (articles) 2nd table with 0376ed32bdf8419cbe1e304befe50f21.jpg
comments on these articles It is
071e159a66c64a93af7980863cebba75.jpg
necessary to display the number of comments for each article, and for those articles where there are no comments, indicate 0
I display all this on the main page of the site. Right here (indicated by the red arrow)
21e885f5ccad46419cb23a1faf3a9684.jpg.
How can I implement this correctly? How to form the correct query to the database, so that later all this can be easily displayed using the foreach loop??

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2015-07-10
@sugarufc

You can use a subquery to select the number of comments immediately when selecting an article.

select a.id, a.title, a.content,
       (select count(*) from comments where article_id=a.id) as comments_count
    from articles as a

L
LittleFatNinja, 2015-07-10
@LittleFatNinja

SELECT count(*) from articles

A
AVKor, 2015-07-10
@AVKor

SELECT 
COUNT(comment_id)
FROM articles
LEFT JOIN comments
ON comments.article_id = articles.id
GROUP BY articles.id;

This only outputs the count. Add whatever else needs to be output to SELECT.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question