Smarty查询计数在另一个查询中

时间:2014-02-24 08:58:04

标签: php mysql smarty

我试图表明每条评论有多少“回复”。

查询:

$sql = "SELECT c.*, a.username, a.avatar FROM user_wall c LEFT JOIN account a ON c.fid=a.id WHERE c.tid='". (int) $user[id]."' AND c.parent IS NULL ORDER BY `cid` DESC LIMIT 0, 10";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0)
{
    $comments = array();
    while ($row = mysql_fetch_assoc($result))
    {
        $cid = $row[cid];
        $comments[] = $row;
        $smarty->assign('comments', $comments);

        // Get how many replies the comment has
        $sql = mysql_query("SELECT count(*) AS `total` FROM `user_wall` WHERE parent='".$cid."'");
        $tmp = mysql_fetch_assoc($sql);
        $smarty->assign('rcount', $tmp['total']);
    }   
}

我在smarty模板上的内容:

{foreach item="comments" from="$comments"}
    <div class="bubble2">
        <div class="clearfix">
        <div class="cinfo">By <a href="#">{$comments.username}</a>, {$comments.time}</div>
        <div style="clear: both;"></div>
            {$comments.comment}
        <div class="c-actions">
            <a href="#"><i class="icon-comments"></i> ({$rcount}) Replies</a>
        </div>
        </div>
        </div>
{/foreach}

user_wall表: enter image description here

结果:

enter image description here

问题在于每个评论现在都说它有“3”回复,而唯一的回复是第2条评论(你好,这是测试!:-))。我怎样才能解决这个问题?对我的想法有更好的方法吗?

提前致谢。

1 个答案:

答案 0 :(得分:2)

$sql = "SELECT c.*, a.username, a.avatar FROM user_wall c LEFT JOIN account a ON c.fid=a.id WHERE c.tid='". (int) $user[id]."' AND c.parent IS NULL ORDER BY `cid` DESC LIMIT 0, 10";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0)
{
    $comments = array();
    while ($row = mysql_fetch_assoc($result))
    {
        $cid = $row['cid'];

        // Get how many replies the comment has
        $sql = mysql_query("SELECT count(*) AS `total` FROM `user_wall` WHERE parent='".$cid."'");
        $tmp = mysql_fetch_assoc($sql);
        $row['rcount'] = $tmp['total'];
        $comments[] = $row;

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



{foreach item="comment" from="$comments"}
    <div class="bubble2">
        <div class="clearfix">
        <div class="cinfo">By <a href="#">{$comment.username}</a>, {$comment.time}</div>
        <div style="clear: both;"></div>
            {$comment.comment}
        <div class="c-actions">
            <a href="#"><i class="icon-comments"></i> ({$comment.rcount}) Replies</a>
        </div>
        </div>
        </div>
{/foreach}