简体   繁体   中英

php counting reply on post

Hi i am having a problem regarding counting rows of reply on post. i am doing a project a simple forum script. i just want to have a reply count on my forum here is the script i made.

$replyCount = mysql_query("SELECT COUNT(id) AS total FROM topic_reply WHERE tid = '".$topic_id."' ");

$row = mysql_fetch_object($replyCount);
$reply_count_rows = $row->total;

The problem is i get the same results for the 2 different topics it goes something like this

Topic 1 / Reply 2

Topic 2 / Reply 2

the **Topic 1** has 2 Replies and the **Topic 2** has no or 0 replies but i am getting same values on both Topics

Hope someone can help me on this thanks in advance.

I'm going to ignore that you're using a deprecated function, and that your query is vulnerable to SQL Injection.

Try this:

 $replyCount = mysql_query("
 SELECT
     IFNULL(COUNT(id), 0) AS total
 FROM
      topic_reply
 GROUP BY
       tid");

Remove the WHERE clause in your query if you want to know the count for each TID.

By filtering the FID, you will only be counting for THAT specific TID.

See this sqlfiddle:

http://sqlfiddle.com/#!2/ea106/4

It could be an issue with $topic_id. Echo it and check if it is the correct one for each topic you are accessing.

And please, as suggested in other comments, use PDO and prevent SQL injections. Read up on them if you are unfamiliar.

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