Hello. Tried to implement a comment system. I wanted to make it so that the number of comments was displayed. Made a theoretically correct query, but it gives an error. Requests in places changed, did not help. Perhaps not.

$post_comments = mysql_query($db,"SELECT COUNT(*) FROM comments WHERE post_id='$post_id'"); $post_comments2 = mysql_fetch_array($post_comments); 

The request does not give the number of records that satisfy the condition, but gives an error:

 mysql_fetch_array() expects parameter 1 to be resource, null given in 

PS There are no records for this condition. The table is empty, but 0 should be issued, it is again not issued. Tell me, what is the error or how to make a request? Thank you in advance!

I tried to make the code like this, the conversion errors disappeared, but returns an array in response, instead of a numeric value:

 $post_comments = mysqli_query($db,"SELECT COUNT(*) FROM comments WHERE post_id='$post_id'"); $post_comments2 = mysqli_fetch_row($post_comments); 
  • MySQL extension is officially out of date, and will soon be made out of PHP. Use MySQLi or PDO. Well this is so, advice for the future - naym

1 answer 1

The mysql_query functions pass the sql query as the first parameter, and the connection identifier as the second. And you have the opposite

Also use the AS keyword if you think something. It is more comfortable.

 SELECT COUNT(*) AS total_comments FROM comments 
  • @mountpoint Tell me, how everything will look right. I tried to do as you said, but again the error does not disappear. Could it be somehow related to the fact that there are no records in the database? - OverLoader