Home >Backend Development >PHP Tutorial >Why Do I Get 'Commands Out of Sync' Errors in My PHP MySQLi Code, and How Can I Fix Them?
Commands Out of Sync: Delving into the Cause and Resolution
When attempting to execute PHP code that utilizes MySQL queries via mysqli, one may encounter the error, "Commands out of sync; you can't run this command now." This error indicates a conflict between the sequential execution of database queries.
The provided PHP code exhibits this issue due to the use of unbuffered queries by mysqli for prepared statements. This means that only the most recently executed query's results are available at any given time.
To resolve this error, two approaches can be taken:
In the provided code, $stmt->store_result() can be used after the first query to buffer its results:
if ($numRecords = $con->prepare($countQuery)) { $numRecords->bind_param("s", $brand); $numRecords->execute(); $numRecords->store_result(); $data = $con->query($countQuery) or die(print_r($con->error)); $rowcount = $data->num_rows; ... }
By implementing one of these solutions, the commands will no longer be out of sync, and the PHP code should execute successfully.
The above is the detailed content of Why Do I Get 'Commands Out of Sync' Errors in My PHP MySQLi Code, and How Can I Fix Them?. For more information, please follow other related articles on the PHP Chinese website!