Saturday, 15 March 2014

mysql - PHP how to loop through multiple comment levels -



mysql - PHP how to loop through multiple comment levels -

my database construction looks (for commenting system):

however, i'm lost on how loop through such data, nested comments/different levels.

currently, loop through info , display level 0 comments, , each level 0 comment, loop through , find it's corresponding level 1 comment. however, there can maximum of 10 levels, , looping through 10 way am, sense inefficient.

the replyto column refers id of comment reply to. if number 0, means comment not reply. table above, example, want loop through php display (from recent oldest):

hello want test good! test page! test

you have options:

lot of queries

you select comments need in loop:

<?php function displaycommentsrecursive($stmnt, $replyto = 0) { // select top comments first $stmnt->execute(array(0)); $result = $stmnt->fetchall(); foreach($result $res) { // display comment echo $res->user , ': ' , $res->text; echo displaycommentsrecursive($res->id); } } $stmntgetcomments = $pdo->prepare(" select id, user, text comment replyto = ? "); displaycommentsrecursive($stmntgetcomments);

lot of iteration

you fire query 1 time , pick comments need out of "comment pool":

<?php function displaycommentsrecursive(array $comments, $replyto = 0) { foreach($result $res) { if($replyto != $res->replyto) continue; // display comment echo $res->user , ': ' , $res->text; echo displaycommentsrecursive($comments, $res->id); } } $stmntgetcomments = $pdo->prepare(" select id, user, text, replyto comment "); // select comments @ 1 time $stmntgetcomments->execute(array(0)); $comments = $stmntgetcomments->fetchall(); displaycommentsrecursive($comments);

php mysql loops nested

No comments:

Post a Comment