Answer the question
In order to leave comments, you need to log in
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
comments on these articles It is
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)
.
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question