I found the below threaded comments example online and the author says it works very well for him. However, I’m having problems ordering the results so the threaded comments are in the right place. This is what the example gives me:
Example author says: “I use a system which is simple and doesn’t rely on recursion. I
basically store the entire thread “path” as a row field. Want to get
the entire tree structure? Just do an ORDER BY on the path column and
use some PHP code like the following for formatting:”
The Example Data
ID | Comment | Path
---+------------------------------+----------
0 | Comment #1 | 00
1 | Comment #1 reply | 00_01
2 | Comment #1 reply reply | 00_01_02
3 | Comment #2 | 00
4 | Comment #3 | 00
5 | Comment #3 reply | 00_04
The Example SQL
SELECT * FROM comments ORDER BY path
The Example PHP
while ($result = mysql_fetch_assoc($query)) {
$nesting_depth = count(explode("_", $result['path']));
$branch = str_repeat("--", $nesting_depth);
echo $branch {$result['comment']}";
}
The Example Result
Comment #1
-- Comment #1 reply
---- Comment #1 reply reply
Comment #2
Comment #3
-- Comment #3 reply
I added the exact data to my MySQL database and tested it and worked as expected. However, if I change the order of the data in the table, it does NOT work. I’ll explain:
New REALISTIC Test Data
ID | Comment | Path
---+------------------------------+----------
0 | Comment #1 | 00
1 | Comment #2 | 00
2 | Comment #3 | 00
3 | Comment #3 reply | 00_04
4 | Comment #1 reply | 00_01
5 | Comment #1 reply reply | 00_01_02
Take a look at row[4] and row[5], these reply comments were the last comments added and drastically changes the order of results:
New Test Results
Comment #1
Comment #2
Comment #3
-- Comment #1 reply
---- Comment #1 reply reply
-- Comment #3 reply
This is a big problem! Is this guy talking absolute rubbish or have I done something wrong? Unless the data is in the exact same order you want to display, it will never work. Is there something simple I can do to fix the order?
Every “main” comment must have a path that contains a unique ID number. In your case every “main” comment has an ID of
00. If you have three of those, then there’s no way to get a reply in between.The last
itemwill alway be the last item (alphabetically). If you distinguish every “main” comment with a unique ID, then the problem is solved.So when you’re going to reply to a comment all you need to do is reference their entire path, and add an indexing key at the end.
In the above table:
etc.
Then again, this is a weird construction. In my opinion an
id/parent_idrelation is better for these kind of things.