我有一个来自第一个sql查询的foreach循环,然后在foreach循环中,我想运行另一个sqli查询,但是我收到了这个错误:Call to a member function prepare() on a non-object
这是我的问题:
$sqli = "SELECT DISTINCT approveby FROM ads LIMIT 0,20";
$resulti = $conn->prepare($sqli);
$resulti->execute();
foreach ($resulti as $rowi){
$sqlii = "SELECT * FROM ads WHERE approveby=:approveby ORDER BY approvedate ASC";
$resultii = $conn->prepare($sqlii);
$resultii->bindParam(':approveby', $rowi['approveby']);
$resultii->execute();
$num_rowsii=$resultii->rowCount();
echo "This person: ". $rowi['approveby']."has approved $num_rowsii advertisements";
}
上述代码的原因是:
有不同的人可以批准来自表格广告的广告。将有一个人批准许多广告。所以第一个查询,我想列出刚刚批准广告的人。
第二个问题,我想计算每个人的总批准数。
那么请告诉我如何解决上面的错误?而且还有更有效地做到这一点吗?
非常感谢
答案 0 :(得分:1)
您可以在单个查询中获得结果,用户GROUP BY
而不是DISTINCT
结果,然后计数结果将显示每个组的总广告,请尝试此查询
$sqli = "SELECT *, count(*) AS `total_advertisements` FROM ads
GROUP BY approveby
ORDER BY approvedate ASC
LIMIT 0,20";
$resulti = $conn->prepare($sqli);
$resulti->execute();
foreach ($resulti as $rowi){
echo "This person: ". $rowi['approveby']."has approved {$rowi['total_advertisements']} advertisements";
}
答案 1 :(得分:0)
该代码根本不会表现良好。相反,将这两个查询组合起来:
$sql = "SELECT approveby, count(*) FROM ads GROUP BY approveby"
$result = $conn->prepare($sql);
$result->execute();