简体   繁体   English

在foreach循环中运行另一个SQL查询

[英]Run another sql query inside foreach loop

I have a foreach loop from the first sql query, then inside that foreach loop, i would like to run another sqli query, but i got this error: Call to a member function prepare() on a non-object 我从第一个sql查询中有一个foreach循环,然后在该foreach循环中,我想运行另一个sqli查询,但出现此错误: Call to a member function prepare() on a non-object

Here is my query: 这是我的查询:

$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";
}

The reason for above code is: 上面代码的原因是:

There are different people who can approve advertisement from table ads. 可以从表格广告中批准广告的人不同。 There will be one person who approve many advertisements. 会有一个人批准许多广告。 So the first query, i would like to list the people who have just approved advertisement. 所以第一个查询,我想列出刚刚批准广告的人。

And the second query, I would like to calculate total number of approvement for each person. 第二个查询,我想计算每个人的批准总数。

SO please tell me how to fix the error above? 所以,请告诉我如何解决以上错误? And also is there anyway to do this more effectively? 还有反正可以更有效地做到这一点吗?

Many thanks 非常感谢

You can achieve result in single query, user GROUP BY instead of DISTINCT result and then count result will show total advertisements of each group set, try this query 您可以通过单个查询获得结果,使用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";
}

That code is not going to perform well at all. 该代码根本无法正常运行。 Instead, combine the two queries like this: 而是将两个查询组合如下:

$sql = "SELECT approveby, count(*) FROM ads GROUP BY approveby"
$result = $conn->prepare($sql);
$result->execute();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM