3

I'm trying to write my MySQL query, but I'm stuck on this - I have multiple queries from my php to the SQL database:

SET @var := SELECT MAX(first_column)
    FROM table;

SELECT @var, 
    table.second_column
FROM table;

But it returns SQL error. When I use it in phpmyadmin, it works fine. I've googled and I saw people use "SET @var = MySQL query" only in stored procedures. Is it possible to use it the way I want?

suricactus
  • 1,210
  • 2
  • 15
  • 22
  • Who's giving you error? Maybe PHP can't run two queries? – Sergio Tulentsev Apr 26 '12 at 21:44
  • possible duplicate of [mysqli multiple queries - set variable produces boolean error/how to skip this?](http://stackoverflow.com/questions/1227022/mysqli-multiple-queries-set-variable-produces-boolean-error-how-to-skip-this) – mellamokb Apr 26 '12 at 21:52
  • Would be nice to know what the text of the SQL error is.... –  Apr 26 '12 at 22:50

2 Answers2

6

If you are running multiple queries (i.e., you have a ; in your query), you either need to run it as two separate queries, or use a command like mysqli_multi_query. The mysql_query command can only run a single query at a time.

mysql_query('SET @VAR := SELECT MAX(first_column) FROM TABLE');
mysql_query('SELECT @var, table.second_column FROM table');

See also this related question.

Community
  • 1
  • 1
mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • Thank you, I didn't know that there could be only one query. I've tried to make multiple queries because I think it would be a slightly faster than separate queries. – suricactus Apr 26 '12 at 22:14
1
SELECT MAX(first_column) INTO @var FROM table; 
SELECT @var,table.second_column FROM table;  
RolandoMySQLDBA
  • 43,883
  • 16
  • 91
  • 132