带有回复的PHP MySQL评论系统

问题描述 投票:-1回答:1

我有能够捕获初始评论和第一级答复的代码,但似乎无法捕获对答复的答复。我知道它需要使用某种形式的递归的不确定代码,但还不确定如何正确实现它。这是我的phpMyAdmin表的样子:

id名称评论reply_id1 BigBadProducer1我爱这个vst!我用它所有的时间! 02 DrummaBoy504嗨,这是Drum Squad的Drumma! 03迈克·史密斯(Mike Smith)您是如何使vst听起来如此出色的... 14 BigBadProducer1是的,我从YouTube的Mike S学习了如何进行调整... 35 SmoothBeatz3 Dude,我一直在寻找这样的vst,以寻求更好的... 06 FanBoy123嘿,Drumma,您打算什么时候发行新专辑... 27 Mike Johnson Hey Fanboy123,你为什么那么喜欢Drum S ... 6

这里是代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<?php
// Create connection
$conn = new mysqli('localhost', 'root', 'mypassword', 'commentsystem2');

$sql1 = "SELECT * FROM comments WHERE reply_id = 0";
$result1 = mysqli_query($conn, $sql1);

while ($comment = mysqli_fetch_array($result1)) {
    $id = $comment['id'];
    $name = $comment['name'];
    $comment = $comment['comment'];
    
echo '
<div class="comments" style="position:relative; margin:auto; width:500px; border:1px solid black; margin-top:1px;">
<div>'.$name.'</div>
<div>'.$comment.'<br><br></div>
</div>
';

$sql2 = "SELECT * FROM comments WHERE reply_id = $id";
$result2 = mysqli_query($conn, $sql2);
while ($reply = mysqli_fetch_array($result2)) {
$id_reply = $reply['id'];
$reply_name = $reply['name'];
$reply_comment = $reply['comment'];
$reply_id = $reply['reply_id'];


echo '
<div class="replies" style="position:relative; margin:auto; width:500px; border:1px solid black; margin-top:1px;">
<div style="width:80%; text-align:center;">'.$reply_name.' replied to '.$name.'</div>
<div style="width:80%; text-align:center;">'.$reply_comment.'<br><br></div>
</div>
';

 }//end of replies while loop

}//end of comments while loop

?>
</body>
</html>
php comments system reply
1个回答
0
投票

递归

这里是递归解决方案的快速示例,它使用数组作为数据库查询的模型。

一些重要说明:

  1. 请注意结构:所有数据获取和操作都在打印出单个内容之前完成。

  2. 作为对象,这会更好,它可以避免函数内的GLOBAL标记,但这可以使您指向该方向。

  3. 递归函数应该始终进行测试,以防万一出错。这个例子不行!您可以使用静态变量来计算递归并在达到一定限制时停止。


<?php

// mock data of "select * from comments"
$dbRows = [
  1 => ['name' => 'BigBadProducer1', 'comment' => 'I love this vst! I use it all the time!', 'reply_id' => 0],
  2 => ['name' => 'DrummaBoy504', 'comment' => 'Hey, this is Drumma from Drum Squad!', 'reply_id' => 0],
  3 => ['name' => 'Mike Smith', 'comment' => 'How did you get the vst to sound so good like that...', 'reply_id' => 1],
  4 => ['name' => 'BigBadProducer1', 'comment' => 'Yes, I learned how to tweak it from YouTube Mike S...', 'reply_id' => 3],
  5 => ['name' => 'SmoothBeatz3', 'comment' => 'Dude, Ive been looking for a vst like this for a l...', 'reply_id' => 0],
  6 => ['name' => 'FanBoy123', 'comment' => 'Hey Drumma, when are you going to release a new hi...', 'reply_id' => 2],
  7 => ['name' => 'Mike Johnson', 'comment' => 'Hey Fanboy123, why are you such a fanboy of Drum S...', 'reply_id' => 6],
  ];

// mock data of "select id from comments where reply_id=?"
$children = [];
foreach($dbRows as $id => $row) {
  $reply_id = $row['reply_id'];
  $children[$reply_id][] = $id;
}

// format row into html
function formatRow($row, $reply_name='unknown') {
    $out =<<<FORMATROW
<div class="replies" style="position:relative; margin:auto; width:500px; border:1px solid black; margin-top:1px;">
<div style="width:80%; text-align:center;">{$row['name']} replied to {$reply_name}</div>
<div style="width:80%; text-align:center;">{$row['comment']}<br><br></div>
</div>
FORMATROW;

    return $out;
}

// mock of database CRUD function "select * from comments where id=?"
function find($id) {
    global $dbRows;
    if(array_key_exists($id, $dbRows)) {
        return $dbRows[$id];
    }
}

// mock of database CRUD function "select id from comments where reply_id=?"
function findChildren($id) {
    global $children;
    if($id == 0) { return []; }

    $out = [];
    if(array_key_exists($id, $children)) {

        $out = $children[$id];
    }
    return $out;
}

function getRepliesTo($id) {

    // test to end recursion
    // if(!$id) { return; }

    // get parent name
    $row = find($id);
    $parent_name = $row['name'];

    // start indented list every time a traversal is called
    $out = "<ul>\n";

    // list of child ids. if no children are found, 
    // assigns an empty array so that foreach won't barf
    $children = findChildren($id);

    foreach($children as $cid) {

        // if there are children, capture their reply and then call this same function to get replies to this reply            
        if($reply= find($cid)) {
            $out .= '  <li>' . formatRow($reply, $parent_name);
            $out .= getRepliesTo($cid);
            $out .= "</li>\n";
        }
    }

    $out .= "</ul>\n";
    return $out;
}

// print_r(find(1));
// print_r(findChildren(1));
// print_r(findChildren(2));
// print traverse(1);

$id = 1; // $id = (int)$_GET['id'];

$commentData = find($id);
$replyHtml = traverse($id);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
  <div class="comments" style="position:relative; margin:auto; width:500px; border:1px solid black; margin-top:1px;">
    <div><?= $replyHtml['name'] ?></div>
    <div><?= $replyHtml['comment'] ?><br><br></div>
  </div>
  <?= traverse($id) ?>
</body>
</html>

材料化路径

另一种方法是使用实​​体化路径查询,这需要对reply_id字段进行些微更改:

$dbRows = [
  1 => ['name' => 'BigBadProducer1', 'comment' => 'I love this vst! I use it all the time!',               'reply_id' => '/0/1'],
  2 => ['name' => 'DrummaBoy504',    'comment' => 'Hey, this is Drumma from Drum Squad!',                  'reply_id' => '/0/2'],
  3 => ['name' => 'Mike Smith',      'comment' => 'How did you get the vst to sound so good like that...', 'reply_id' => '/0/1/3'],
  4 => ['name' => 'BigBadProducer1', 'comment' => 'Yes, I learned how to tweak it from YouTube Mike S...', 'reply_id' => '0/1/3/4'],
  5 => ['name' => 'SmoothBeatz3',    'comment' => 'Dude, Ive been looking for a vst like this for a l...', 'reply_id' => '/0/5'],
  6 => ['name' => 'FanBoy123',       'comment' => 'Hey Drumma, when are you going to release a new hi...', 'reply_id' => '/0/2/6'],
  7 => ['name' => 'Mike Johnson',    'comment' => 'Hey Fanboy123, why are you such a fanboy of Drum S...', 'reply_id' => '/0/2/6/7'],
  ];

想找到2的所有后代吗? select * from comments where reply_id like '/0/2%'

© www.soinside.com 2019 - 2024. All rights reserved.