Note that there are some explanatory texts on larger screens.

plurals
  1. PONested while loops
    text
    copied!<p>I have a system of comments. Each comment may receive replies, and each reply may receive replies, ad nauseam.</p> <p>Thus, my database contains a table named "comments" with the following important fields:</p> <pre><code>id text reply_to </code></pre> <p>...under reply_to, of course, goes the id of the comment to which it is a reply.</p> <p>So now, the problem is simple: how do I display all the comments, but knowing that after each comment must come the replies to it, and after each reply must come the replies to the reply, etc?</p> <p>What I tried the most, and what I keep coming back at, is something like this:</p> <pre><code>$query = mysql_query("SELECT * FROM comments WHERE reply_to=0"); while ($comment = mysql_fetch_array($query)) include("comment.php"); </code></pre> <p>And in comment.php, what I have is:</p> <pre><code>foreach ($comment as $key = $value) $$key = $value; echo $text; echo "&lt;div style='margin-left:30px;'&gt;"; //A margin for a little indent $subquery = mysql_query("SELECT * FROM comments WHERE reply_to=$id"); while ($comment = mysql_fetch_array($subquery)) include("comment.php"); echo "&lt;/div&gt;"; </code></pre> <p>But if I reproduced correctly the essence of my code, the problem is this: that after the first reply is echoed, it goes on to the first reply of the first reply, and then the first reply of the first reply of the first reply, but the loop never gets to the second reply of anything. So for example, supposing the table had 3 comments, each of which had 3 replies, and each of which had 3 replies, etc, the above code would output:</p> <pre><code>Comment First reply First second-order reply First third-order reply ... </code></pre> <p>I hope I have explained it clearly enough. inb4: I cannot add new columns to the table. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload