/    Sign up×
Community /Pin to ProfileBookmark

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 what my phpMyAdmin table looks:
https://i.ibb.co/TKc9rZm/comments-Table1.png![https://i.ibb.co/TKc9rZm/comments-Table1.png](src)

Here’s the code:

`<?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.
https://i.ibb.co/XxcrWMs/replies-missing.png![https://i.ibb.co/XxcrWMs/replies-missing.png](src)

to post a comment
PHP

0Be the first to comment 😎

×

Success!

Help @AaronEsteban spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...