I have a query that is working fine when I run in through phpMyAdmin directly as SQL, but when I try and do this in PHP it doesn’t work. I suspect the problem is because I’m trying to return a rownum value from a generated table and the SET command on the first line doesn’t work. Here is an example query that is working as expected as SQL:
SET @rownum =0;
SELECT * FROM (
SELECT i.*, @rownum := @rownum +1 AS row, (
SELECT COUNT( * )FROM _votes WHERE i.id = image_id) AS total_votes,
(SELECT COUNT( * ) FROM _votes WHERE i.id = image_id AND voter_id = 67) AS voted
FROM _images AS i WHERE i.approved = 1 ORDER BY total_votes DESC )
AS T WHERE entrant_id IN (68,69,70,71)
(please forgive my formatting if it is incorrect)
Two things:
- Is this query too long and inefficient?
- How do I initialize the @rownum value to zero if this is coming from a php prepared statement?
I’ve tried adding JOIN (SELECT @rownum :=0) r to the end of the query but that doesn’t work.
Also I’ve tried this joining method unsuccessfully at various points within the query.
php
$query = "SELECT * FROM ( SELECT i.*, @rownum := ...
SETqueries are distinct queries, and you can only send one query at a time through PHP. So, run theSETquery, then run the second query. The MySQL server will remember your setting if you use the same connection.