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.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay