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
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
$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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.