DEV Community

Cover image for PHP Comment System With Replies
aaronesteban1
aaronesteban1

Posted on

2

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:

<?php
$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>
      <div>'.$c_comment.'<br><br></div>
   </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>
             <div>'.$r_comment.'<br><br></div>
          </div>
          ';

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

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

$conn->close();
?>

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more