How to loop through sql sum results in PHP?
I need to sum up the result of the total column:
SELECT SUM(number_guest) AS total, booking_time
FROM mt_bookingtable
WHERE
merchant_id IN (SELECT merchant_id
FROM mt_merchant
WHERE merchant_id = 1 )
AND booking_time BETWEEN "12:00" AND "20:00"
AND
date_booking like "2020-06-01"
AND status in ('pending','approved')
GROUP BY booking_time
I tried to use foreach like this:
foreach ($res as $item) {
$sum += $item['total'];
return $sum;
}
But I got the result null
.
Answer
Solution:
Remove the GROUP BY
:
SELECT SUM(number_guest) AS total
FROM mt_bookingtable
WHERE merchant_id IN (SELECT merchant_id FROM mt_merchant WHERE merchant_id = 1 ) AND
booking_time BETWEEN '12:00' AND '20:00' AND
date_booking like '2020-06-01' AND
status in ('pending', 'approved');
Source