I’m using MySQL 5.7 and PHP 7.4.
The following select statement runs perfectly fine in phpMyAdmin and returns a row, as I would expect.
select b.price,sum(ifnull(i.itemamount,0)) totalpaid,b.loyaltypoints
from bookings b
left join paymentitems i on i.bookingid = b.id
where b.id = 214
But if I try to run this exact same statement from within PHP using PDO, I get a 500 error. And yes, I’ve confirmed that the value I’m binding to :bookingid is 214.
$db->query("select b.price,sum(ifnull(i.itemamount,0)) totalpaid,
b.loyaltypoints
from bookings b
left join paymentitems i on i.bookingid = b.id
where b.id = :bookingid");
$db->bind(":bookingid",$bookingid);
I’ve narrowed the problem down to this part
sum(ifnull(i.itemamount,0)) totalpaid
If I remove the sum, then it works. At least in the sense that it considers it valid SQL and it runs. Of course I don’t get the result I want because I need the sum value.
ifnull(i.itemamount,0) totalpaid
So I guess this is a two part question. Most importantly, how can I make this work, but also, why does it not work? This boggles my mind.
EDIT: I should add, since there seems to be a lot of confusion about my syntax, that I’m using a database class to prepare and bind, so when I say $db->query() this is actually doing a prepare. And the $db->bind() is doing a bindValue. I’ve been using this class for years on thousands of other statements and have never had this problem before so I know it works just fine.
EDIT: Found this error in the PHP logs: PHP Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column ‘benji_prod.b.price’; this is incompatible with sql_mode=only_full_group_by in
2
Answers
The error message states that you need all Columns to have a aggregation function like below.
But i think you need to rethink your query and show us what you really want to accomplish, with your query
It seems, that phpmyadmin ignores the only_full_group_by of the server. But the solition here to disable it, isn’t the right choice, write a correct query, that delivers the correct result
db<>fiddle here