I searched through the forums but couldn\'t get an authoritative answer. I want to implement a nested comment structure in a way like this:
&l
There are several different ways to store heirarchical data in MySQL. Check out Bill Karwin's presentation that demonstrates four options.
You are using the adjacency list model for storing heirarchical data, but unfortunately this is the hardest model you could choose for querying subtrees.
Your options are:
I had done something similar for my blogpost. Yet, I just tried out with the same data. When you say nested comments it is better you can use nested functions this way:
function getComments($parent)
{
# Get the data from SQL.
# Check if it has nested comments.
if (hasComments())
getComments($child); # $child is the ID of the current comment.
}
To make it this way, I have imported your data to MySQL and tried this:
<?php
mysql_connect('localhost', 'root');
mysql_select_db('nestedcomments');
function getComments($parent)
{
$res = mysql_query("SELECT * FROM `nestcomm` WHERE `parent` = $parent");
if (mysql_num_rows($res))
{
echo "<ul>\n";
while (($dat = mysql_fetch_array($res)) !== false)
echo "<li>", $dat["text"], getComments($dat["id"]), "</li>\n";
echo "</ul>\n";
}
else
echo ($parent === 0) ? 'No Comments!' : "";
}
getComments(0);
?>
As I said before I have used nested functions, and as you asked the output is almost same (without the braces) this way:
<ul>
<li>This is the parent first comment!<ul>
<li>This is the reply for the first parent comment!<ul>
<li>This is a reply for the first reply of the parent comment!</li>
<li>This is a third reply for the first parent comment!</li>
</ul>
</li>
<li>This is another reply for first parent comment!</li>
</ul>
</li>
<li>This is gonna be parent second comment!<ul>
<li>This is a reply for the second comment!</li>
</ul>
</li>
<li>This is fourth parent comment!</li>
</ul>
Hope this helps out.