一些帮助回复评论PHP

时间:2014-03-16 22:07:45

标签: php smarty

有人可以在我的评论系统添加回复方面给我一些帮助。

我在Smarty 3上创建了一个项目,到目前为止我已经完成了评论部分,但我在回复部分遇到了一些麻烦,因为它没有显示回复可能是某人检查我的代码,看看我做错了什么或为我更正请在这里,我的代码如下。

电影类的PHP函数

public function GetMovieComments($con, $movie_id) {
    $c = array();
    $q = mysqli_query($con,"SELECT * FROM `movie_comments`,`user` WHERE `movie_id` = '".$movie_id."' AND `uid` = `user_id`");
    if (mysqli_num_rows($q) > 0) {
        while ($r = mysqli_fetch_assoc($q)) {
            $c[] = $r;
        }
        return $c;
    }   
}

public function GetMovieReplies($con, $comment_id) {
    $comment_id = mysqli_real_escape_string($con, $comment_id);
    $rp = array();
    $q = mysqli_query($con,"SELECT * FROM `movie_replies`,`user` WHERE `comment_id` = '".$comment_id."' AND `uid` = `user_id`");
    if (mysqli_num_rows($q) > 0) {
        while ($r = mysqli_fetch_assoc($q)) {
            $rp[] = $r;
        }
        return $rp;
    }   
} 

现在从movie.php调用函数

$comments = $movie->GetMovieComments($con, $movie_id);

if (isset($comments)) {
    foreach($comments as $comment) {
        $comment_id = $comment['cid'];
        $replies = $movie->GetMovieReplies($con, $comment_id);
        $smarty->assign('replies',$replies);
    }
}

$smarty->assign('comments', $comments);

现在在movie.tpl

{if isset($comments)}
    {if $comments neq ''}
        {foreach from=$comments key=key item=comment}
            <div class="media">
                <div class="media-body">{$comment.comment}</div>
            </div>
            {foreach from=$replies key=key item=reply}
                <h4>{$reply.reply}</h4>
            {/foreach}
        {/foreach}
    {else}
        <h5>No Comments</h5>
    {/if}
{/if}

有人可以帮助我,我一直在努力解决这个问题吗?lol谢谢

1 个答案:

答案 0 :(得分:0)

为了不覆盖变量回复,我会做这样的事情:

// Make GetMovieComments return an array with values or simply an array(), so no check needed
$comments = $movie->GetMovieComments($con, $movie_id);

foreach($comments as $key => $comment) {
  $replies = $movie->GetMovieReplies($comment['cid']);
  $comments[$key]['replies'] = $replies;
  }

$smarty->assign('comments', $comments);

然后您可以访问{foreach from=$comment.replies key=key item=reply}以在内部foreach中使用它。然而,这只是一件事,代码中可能会出现更多错误......

我会用你的代码做一些额外的事情:

public function GetMovieComments($movie_id) {
    $comments = array();
    // Some data validation to avoid SQL Injections
    // You might be better with binding parameters if it's not an int
    $id = intval($movie_id);
    // You use the connection already stored in this object. You should set it in the constructor
    $query = mysqli_query($this->con,"SELECT * FROM `movie_comments`,`user` WHERE `movie_id` = '" . $id . "' AND `uid` = `user_id`");
    // No need for the if. This will only enter if there's any result anyway
    while ($result = mysqli_fetch_assoc($query)) {
        $comments[] = $result;
        }
    return $comments;
    }

// Apply some similar changes to GetMovieReplies() as the ones above.