一个博客程序 要根据首页打印出来的博客标题查出来有多少评论数量,之前没有使用smarty模板引擎的写法如下:
以下代码在index.html页面
`$article=$sql->("SELECT * FROM article");
while($result=$article->fetch_assoc()){
echo $result['id'].$result['title'].$result['content'];//这里打印出来id 标题和内容
$comment=$sql->("SELECT count(*) as sum FROM comment where article_id='$result['id']'");//根据文章的编号查出来对应的评论数量
$sum_comment=$comment->fetch_assoc();
echo $sum_comment['sum'];//这里打印出来评论数量
};
`
但是在smarty里面 查询语句写在了index.php里面 前台index.html显示如下:
{{foreach $article as $result}}{{$result.id}}{{/foreach}}
所以现在导致了我不知道怎么去通过文章的id查询评论数量,求大佬们解答,谢谢大家了!
1.SELECT a.id, b.count() FROM article a inner join comment b on a.id = b.article_id group by a.id having b.count() > 0;
用这个sql直接可以查出每个文章对应的评论数;
2.用你这方法:
`$article=$sql->("SELECT * FROM article");
$comments = [];
while($result=$article->fetch_assoc()){
echo $result['id'].$result['title'].$result['content'];//这里打印出来id 标题和内容
$comment=$sql->("SELECT count(*) as sum FROM comment where article_id='$result['id']'");//根据文章的编号查出来对应的评论数量
$sum_comment=$comment->fetch_assoc();
$comments['$result['id']] = $sum_comment['sum'];
};
{{foreach $comments $key => $result}}{{'文章'$key.'评论总数为'.$result}}{{/foreach}}