I've looked at about a dozen posts about queries not working in PHP, but they all haven't been able to solve my problem - hopefully this is an easy one!
What I am attempting to do here is "rank" the rows based on their total yearly sales, and that's worked pretty well so far. When I run my query in MySQL, it works properly - I get back hundreds of results.
SET @row_number := 0;
SELECT @row_number := @row_number + 1 AS row_number,
TotalRevenue,
CompanyID
FROM (
SELECT CompanyID,
SUM(Sales_Amt) AS TotalRevenue
FROM Sales,
(SELECT @row_number := 0) r
GROUP BY CompanyID
) t
WHERE TotalRevenue > 0
ORDER BY TotalRevenue DESC
Produces:
row_number | TotalRevenue | CompanyID
-----------+--------------+----------
1 | 81130.00 | 333
2 | 72234.00 | 876
3 | 62653.00 | 123
4 | 54408.40 | 999
5 | 44548.00 | 111
However, when I run it via PHP, I get back the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @row_number := @row_number + 1 AS row_number, TotalRevenue' at line 2
Based on other posts here, I've tried:
- adding `` around my column names
- adding '' around my column names
- adding := instead of = when I created @row_number
- confirming that all spaces are added in after my query in PHP so that key words are not squished together
- setting my mysqli->charset to utf-8
Here's my PHP code, in case you need that as well:
$query = "SET @row_number := 0;
SELECT @row_number := @row_number + 1 AS `row_number`,
TotalRevenue,
CompanyID
FROM (
SELECT CompanyID,
SUM(`Sales_Amt`) AS TotalRevenue
FROM Sales
GROUP BY CompanyID
) t
WHERE TotalRevenue > 0
ORDER BY TotalRevenue DESC";
if (!$result = $mysqli->query($query))
{
print_r($mysqli->error);
}
Hoping this will be something really simple that I am just NOT seeing.
Thanks!