我正在为 id = '3' 的产品加载评论
$get_comments = mysql_query("SELECT * FROM products_comments WHERE product_id = '3'");
现在我想为每个评论添加“报告滥用”选项,为此我有另一个表“abuse_reports
”,用户滥用报告将存储在这个表中,现在如果用户报告评论,report abuse
选项不应该再为该用户的评论提供,为此我正在做:
while($row = mysql_fetch_array($get_comments)){
echo blah blah blah // comment details
// now for checking if this user should be able to report this or not, i make this query again:
$check_report_status = mysql_query("SELECT COUNT(id) FROM abuse_reports WHERE reporter_user_id = '$this_user_id' AND product_id = 'this_product_id'");
// blah blah count the abuse reports which the current user made for this product
if($count == 0) echo "<a>report abuse</a>";
}
使用上面的代码,对于每个评论,我都在进行一个新的查询,这显然是错误的,我应该如何将第二个查询与第一个查询连接起来?
谢谢
最佳答案
更新的查询(现在正在运行,由提问者提交)
SELECT pc. * , count( ar.`id` ) AS `abuse_count`
FROM `products_comments` pc
LEFT OUTER JOIN `abuse_reports` ar ON pc.`id` = ar.`section_details`
AND ar.`reporter_id` = '$user_id'
WHERE pc.`product_id` = '$product_id'
GROUP BY pc.`id`
LIMIT 0 , 30
查询的工作方式如下:您使用给定的 product_id
选择了 products_comments
的所有字段,但您还计算了 abuse_reports
的条目对于给定的 product_id
。现在您 LEFT JOIN
abuse_reports
,这意味着您访问该表并将其卡在左侧(您的 products_comments 表)。 OUTER 允许在 abuse_reports 表中不需要值,因此如果没有报告,您将得到 null,因此计数为 0。
请阅读:
但是,我需要对结果进行分组,否则结果只会得到一个合并行。因此,请使用 int
类型的字段 comment_id
扩展您的 products_comments
,该字段是 primary key
并且具有 auto_increment
.
更新:滥用计数 现在您可以做两件事:通过遍历结果,您可以查看每个元素是否已被该用户报告(例如,这样您可以隐藏滥用报告链接)。如果你想要报告的总数,你只需增加一个你在循环外声明的计数器变量。像这样:
$abuse_counter = 0;
while($row = mysql....)
{
$abuse_counter += intval($row['abuse_count']); // this is 1 or 0
// do whatever else with that result row
}
echo 'The amount of reports: '.$abuse_counter;
只是一个原始样本
关于php - 加载评论时加入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17359628/