Home >Backend Development >PHP Tutorial >Why Do I Get a 'Commands Out of Sync' Error in PHP with MySQL Queries?
"Commands Out of Sync" Error in PHP Code with MySQL Queries
When executing a PHP script that involves multiple MySQL queries using mysqli, an error can occur: "Commands out of sync; you can't run this command now." This issue arises when subsequent queries are attempted before fetching and processing the results from the previous query or clearing the MySQL server's cache of query commands.
The code provided in the question executes two queries: one to count records and another to retrieve rows based on a search string. However, before the results of the first query are fetched, the second query is executed. This triggers the "out of sync" error.
Causes of the Error
Possible Solutions
Example
Here's an example of buffering the first query's results using $stmt->store_result():
<?php $con = mysqli_connect("localhost", "user", "password", "db"); $brand ="o"; $countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %"; $con->query("SET NAMES 'utf8'"); if ($numRecords = $con->prepare($countQuery)) { $numRecords->bind_param("s", $brand); $numRecords->execute(); $numRecords->store_result(); // Buffer the results $data = $con->query($countQuery) or die(print_r($con->error)); $rowcount = $data->num_rows; }
The above is the detailed content of Why Do I Get a 'Commands Out of Sync' Error in PHP with MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!