Commands out of sync; you can't run this command now
Solution 1:
You can't have two simultaneous queries because mysqli uses unbuffered queries by default (for prepared statements; it's the opposite for vanilla mysql_query
). You can either fetch the first one into an array and loop through that, or tell mysqli to buffer the queries (using $stmt->store_result()
).
See here for details.
Solution 2:
I solved this problem in my C application - here's how I did it:
-
Quoting from mysql forums:
This error results when you terminate your query with a semicolon delimiter inside the application. While it is required to terminate a query with a semicolon delimiter when executing it from the command line or in the query browser, remove the delimiter from the query inside your application.
-
After running my query and dealing with the results [C API:
mysql_store_result()
], I iterate over any further potentially pending results that occurs via multiple SQL statement execution such as two or more select statements (back to back without dealing with the results).The fact is that my procedures don't return multiple results but the database doesn't know that until I execute: [C API:
mysql_next_result()
]. I do this in a loop (for good measure) until it returns non-zero. That's when the current connection handler knows it's okay to execute another query (I cache my handlers to minimize connection overhead).This is the loop I use:
for(; mysql_next_result(mysql_handler) == 0;) /* do nothing */;
I don't know PHP but I'm sure it has something similar.
Solution 3:
I had today the same problem, but only when working with a stored procedure. This make the query behave like a multi query, so you need to "consume" other results available before make another query.
while($this->mysql->more_results()){
$this->mysql->next_result();
$this->mysql->use_result();
}
Solution 4:
I call this function every time before using $mysqli->query, and it works with stored procedures as well.
function clearStoredResults(){
global $mysqli;
do {
if ($res = $mysqli->store_result()) {
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
Solution 5:
Once you used
stmt->execute();
You MAY close it to use another query.
stmt->close();
This problem was hunting me for hours. Hopefully, it will fix yours.