DEV Community

Cover image for PHP Comment System With Replies

Posted on

PHP Comment System With Replies

I have code that is able to capture the initial comment and the 1st level of replies, but it doesn’t seem to capture the reply to a reply. I know that it requires an indefinite code using some form of recursion, but not quite sure how to properly implement it. Here's the code I'm using:

$conn = new mysqli('localhost', 'root', 'Jordan123', 'commentsystem2');

$sql1 = "SELECT * FROM comments WHERE r_to = 0";
$result1 = $conn->query($sql1);

while($row1 = $result1->fetch_assoc()) {
$c_id = $row1['id'];
$c_name = $row1['name'];
$c_comment = $row1['comment'];

   echo '
   <div class="comments" style="position:relative; margin:auto; width:25%;">
      <div>ID# '.$c_id.'</div>
      <div style="font-weight:bold;">'.$c_name.'</div>

   $sql2 = "SELECT * FROM comments WHERE r_to = $c_id";
   $result2 = $conn->query($sql2);

      while($row2 = $result2->fetch_assoc()) {
          $r_id = $row2['id'];
          $r_name = $row2['name'];
          $r_comment = $row2['comment'];
          $r_to = $row2['r_to'];
          echo '
          <div class="comments" style="position:relative; margin:auto; width:25%; padding-left:80px;">
             <div>ID# '.$r_id.'</div>
             <div style="font-weight:bold;">'.$r_name.' replied to '.$c_name.'</div>

      }//end of 1st while loop that captures comments.

}//end of 1st while loop that captures comments.


Notice how some of the replies to replies that are in the table, are missing on output.

Discussion (2)