How to avoid MySQL "Commands out of sync" error

Jonathan Greenberg
Jonathan Greenberg used Ask the Experts™
on
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?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
lcohanDatabase Analyst

Commented:
"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
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
When running a multi query, you need to loop through all result sets before moving on. If you don't need to retrieve anything from the DB, then you can effectively flush the result sets with calls to mysqli_next_result():

    $result = mysqli_multi_query( $conn, $sql ) or die( "Query Error: " . mysqli_error( $conn ) );
    while(mysqli_more_results($conn)) {
        mysqli_next_result($conn);
    }
    $i++;
}

Open in new window

Author

Commented:
Chris,

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

Regards,
Jonathan
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
No worries Jonathan. Glad I could help :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial