php - 如何使用递归函数嵌套对评论的回复

标签 php

所以,我在评论表中有一个“父”列,我这样称呼评论...

SELECT 
    id, 
    parent_id, 
    member, 
    name, 
    email, 
    ip, 
    comment, 
    img, 
    date 
FROM cs_comments 
WHERE (row_id='$cmtid' AND page_type='$cmtt') 
ORDER BY date

我这样调用这个函数... `

$comment_data = array();

while ($comments_array = $comments->fetch_object()) {
        $comment_data[] = $comments_array;
}

echoComments($comment_data, $memberlevel);

我有一个打印评论的功能设置,但是如何打印回复?该功能在其内部。

如果我的问题不清楚,我可以添加更多信息。

最佳答案

首先,您应该考虑直接在 SQL 查询中使用用户输入数据而不对其进行清理,这是非常危险的,不推荐这样做!


2) 最好将 parent_id 的默认值设置为 0,我不确定 null 是否会得到相同的结果


3) 您可以在 mysql 查询中转义日期和名称列,它可能与 mysql 本地变量和函数冲突

<?php
//Code in view
$comments = getComments($cmtid,$page_type);
echoComments($comment);



//This method will take all Comments with their replies at once;
function getComments($cmtid,$page_type,$parent=0)
{
     GLOBAL $mysqli;
     $comments = $mysqli->query("SELECT `id`,parent_id,member,`name`,email,ip,`comment`,img,`date` 
                                FROM cs_comments 
                                WHERE (row_id='{$cmtid}' AND page_type='{$cmtt}' AND parent_id = {$parent}) 
                                ORDER BY date(format)");
     $comment_data = array();
     while($comments_array = $comments->fetch_object())
     {
        $comments_array->replies = $comments_array->parent_id ? getComments($cmtid,$page_type,$comments_array->parent_id) : array();
        $comment_data[] = $comments_array;
     }
     return $comment_data;
}


//This method will print comment with replies
function echoComments($comment_data)
{
    foreach ($comment_data as $comment):
        echo    '<div class="comment">
                    '.$comment->comment.'
                    <hr />
                    '.echoComments($comment->replies).'
                </div>';
    endforeach;
}

?>

您可以使用此样式表为嵌套回复提供一些缩进:

<style>
.comment{
    background:#fff;
}
.comment .comment{
    margin-left:5px;
    background:#eee;
}
<style>

关于php - 如何使用递归函数嵌套对评论的回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258311/

相关文章:

javascript - 在 php 中使用 Ajax 传递复选框值的(动态)列表

php - Laravel 4 图片上传

php - 从另一个具有最新条目的表中选择值

php - 比较一个表中的两列

php - 如何在服务器的htaccess中更改php版本

javascript - 禁止访问该服务器

php - 计算行数并与给定数字进行比较

php - 在这种情况下如何循环查询?

PHP while 循环和表

php - 如何从数据库中获取不同的数据?