简体   繁体   中英

How to pass sql query with sql variables in php

I want to pass following sql query in php

SET @rank=0; SELECT @rank:=@rank+1 AS rank, `percentage_obtained`  FROM `result`  ORDER BY percentage_obtained DESC

As here

mysql_query('SET @rank=0; SELECT @rank:=@rank+1 AS rank, `percentage_obtained`  FROM `result`  ORDER BY percentage_obtained DESC') or die(mysql_error());

But it throws following 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 @rank := @rank +1 AS rank, percentage_obtained FROM result ' at line 1

However it works when I run the query directly inside the database. Please assist.

mysql_query() doesn't support multiple queries, so you need to separate them. Also you can use mysqli_multi_query - but note, that you need mysqli instead of mysql

So

mysql_query('SET @rank=0') or die(mysql_error());
mysql_query('SELECT @rank:=@rank+1 AS rank, `percentage_obtained`  FROM `result`  ORDER BY percentage_obtained DESC') or die(mysql_error());

should handle this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM