简体   繁体   中英

How to add IF condition in a WHILE loop

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"]. "&nbsp;&nbsp;&nbsp;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?

  1. As @midhat has pointed just use where clause of your query so if condition no longer required.
  2. you can try this one
while($row = $result->fetch_assoc()) {
      if( $row["post_id"]==$post_id ){
          echo  "User " .$row["user_id"]. "&nbsp;&nbsp;&nbsp;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"]. "&nbsp;&nbsp;&nbsp;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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM