For my blogging system I want to have comments and there is going to be a string that displays how many comments are in the post. My tables are set up like so (just examples) post - id - title - cont comment - id - postid - cont Here is the code I am using to make sure to display the comments to their corresponding post. if ($postRow1['id'] = $commentRow['postid']) { echo $commentRow['cont']; } Code (markup): How do I count how many comments are in that specific post and then display the number of comments?
$totalrows = mysql_num_rows(mysql_query("SELECT `id` FROM `comment` WHERE `postid` = '{$postRow1['id']}'")); // print out comments echo $totalrows; PHP: Something like that?
Personally I would use: mysql_query("SELECT count(`ID`) as Total WHERE `postid` = '" . $postRow1['id'] . "'"); However, I would also merge the query to get your entries with this one to make one query ...
I create a function to do this and just do something like $count = dbcount("SELECT * FROM table where field = thing"); function dbcount($query) { $con = mysql_connect("#SERVER#","#USER#","#PASS#"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("#DBNAME#", $con); $result = mysql_query($query) or die(mysql_error()); $num_rows = mysql_num_rows($result); mysql_close($con); return $num_rows; } PHP: