My code:
$sql = "SET @row_number = 0; SELECT (@row_number:=@row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '".$data[2]."' OR o = '".$data[4]."' ORDER BY CASE WHEN player = '".$user_class->id."' THEN 1 ELSE 2 END";
$result = mysql_query($sql) or die(mysql_error());
The error:
You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near ‘SELECT (@row_number:=@row_number + 1) AS num, player,
reinforcees, reinforcers F’ at line 1
When I echo the SQL statement, I get the following: SET @row_number = 0; SELECT (@row_number:=@row_number + 1) AS num, player, reinforcees, reinforcers FROM _KoT_villages WHERE o = '1' OR o = '5' ORDER BY CASE WHEN player = '2' THEN 1 ELSE 2 END
When I run that echo
d statement through phpMyAdmin, it runs successfully, and gives me rows of results.
But why doesn’t it work in a PHP statement? What’s going on? How do I get PHP to do what SQL is doing?
And before anyone says I haven’t tried to find the answer myself, if you Google "sql variable" php site:stackoverflow.com
, every question I find is about accessing SQL results in PHP (i.e., loops) or inserting PHP variables in SQL, which is not what I need. I’m trying to insert an SQL variable into the SQL statement.
Also: I realize I should stop using MySQL, and am in the process of converting, but in order to quickly resolve a bug…I’m using MySQL.
2
Answers
The MySQL client in php expects individual statements
Open MySQL client
First Statement:
2nd Statement:
Close MySQL client
mysql_query
doesn’t support multiple queries in one call. You would need to upgrade tomysqli
orPDO
to enable that. In the meantime though, you can implement what you want in a single query using aCROSS JOIN
to initialise therow_number
variable e.g.