0

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.

5
  • I have an idea that this - @rank:=@rank is a problem, because it is a digit. It provides like this - SELECT 4 AS rank etc. Commented Mar 4, 2017 at 20:35
  • But this give right out put when I use it directly inside the MySQL db Commented Mar 4, 2017 at 20:38
  • Please do a print_r(your query); and post here. Also you set @rank=0, and then do an increment. Why don't do a SELECT 1 ? Commented Mar 4, 2017 at 20:40
  • Found the answer ) Commented Mar 4, 2017 at 20:42
  • Here it is: 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 Commented Mar 4, 2017 at 20:44

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, But how can I do it?
Just split into 2 queries
Then it says: No database selected
Use mysql_select_db ('your database'); before queries.
Database is already connected; it out put single queries without any errors.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.