Link to home
Start Free TrialLog in
Avatar of Jonathan Greenberg
Jonathan GreenbergFlag for United States of America

asked on

How to avoid MySQL "Commands out of sync" error

I have a php while loop that I need to increment through a MySQL multi query. The first time around, it writes to the database as intended. But as soon as it loops around once, I get the following Query Error:

Commands out of sync; you can't run this command now

Here's the loop containing the query:

$i = 285;
while ( $i <= 286 ) {
	$sql = "
		CREATE TEMPORARY TABLE links_temp SELECT * FROM links WHERE 
			schoolid = 0 
			AND planid >= 8000
			AND planid <= 8005;	
		UPDATE links_temp SET linkid = NULL, schoolid = {$i} WHERE 
			schoolid = 0;
		INSERT INTO links SELECT * FROM links_temp;
		DROP TEMPORARY TABLE IF EXISTS links_temp;
	";
	$result = mysqli_multi_query( $conn, $sql ) or die( "Query Error: " . mysqli_error( $conn ) );
	$i++;
}

Open in new window


What do I need to do to enable this query to loop successfully?
Avatar of lcohan
lcohan
Flag of Canada image

"This can happen, for example, if you are using mysql_use_result() and try to execute a new query before you have called mysql_free_result(). It can also happen if you try to execute two queries that return data without calling mysql_use_result() or mysql_store_result() in between."
https://dev.mysql.com/doc/refman/8.0/en/commands-out-of-sync.html
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jonathan Greenberg

ASKER

Chris,

Thank you SO much - it would have taken me hours to figure that out!

Regards,
Jonathan
No worries Jonathan. Glad I could help :)