I'm trying to make simple comments on posts. Adding comments I've successfully completed but I have a problem displaying them. I use this code:
<?php
require "config.php";
$sql = "SELECT post_id, user_id, comment FROM comments";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "User " .$row["user_id"]. " add comment: ".$row["comment" ]."</br>";
}
}
else { echo "No comments for this post";}
?>
I must add a condition in the WHILE loop:
if $row["post_id"]==$post_id
so comments are only displayed on posts for which they are written. ($post_id is defined previously). How can I do it?
where
clause of your query so if condition no longer required. while($row = $result->fetch_assoc()) {
if( $row["post_id"]==$post_id ){
echo "User " .$row["user_id"]. " add comment:".$row["comment" ]."</br>";
}
}
You can only fetch comments with specific post_id
and don't need to apply any if condition as below:
<?php
require "config.php";
$sql = "SELECT post_id, user_id, comment FROM comments where post_id = ".$post_id;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "User " .$row["user_id"]. " add comment: ".$row["comment" ]."</br>";
}
}
else { echo "No comments for this post";}
?>
Hope it helps you.
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.