I have a news and comment system where I want to see the number of comments for a particular news item. I tried many ways but most of them show me the number of all comments in the table but not the number of specific news. How should this be done?
I have table comments with id , nid(news id) comment and author.i tried this method but it shows me the number of all comments from the whole table.
$query = "SELECT * FROM comments ORDER BY nid";
$stmt = $db->prepare($query);
$stmt->execute();
$numberOfComments = $stmt->rowCount();
echo "(<a href=\"comments.php?id=".$id."\">Add Comment</a>) <hr> Comments ( ".$numberOfComments." )";
There is my SQL file comments.sql
CREATE TABLE `comments` (
`id` int(11) NOT NULL,
`nid` int(11) NOT NULL,
`c_title` varchar(70) NOT NULL,
`c_author` varchar(50) NOT NULL,
`comment` text NOT NULL,
`dateAdded` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `comments` (`id`, `nid`, `c_title`, `c_author`, `comment`,`dateAdded`)
VALUES(1, 1, 'My 1st comment', 'User', '1st comment text', '14/08/2019 , 10:55:32'),
(2, 1, 'My 2nd comment', 'Admin', '2nd comment here', '14/08/2019 , 10:56:58'),
(3, 2, 'Comment test here', 'User', 'Comment test here', '14/08/2019 ,10:57:10');
In this case, I have a product to which I add a comment. I want to know how many comments each product has but I can't handle it. "nid" is my product ID.