MySQL: Commands Out of Sync Error
Issue:
Users encounter the "Commands out of sync; you can't run this command now" error when attempting to execute multiple MySQL queries sequentially using mysqli.
Cause:
This error occurs because mysqli uses unbuffered queries by default for prepared statements. This means that the results of the first query must be retrieved before executing the next.
Solution:
There are two ways to resolve this issue:
Method 1: Fetching Results into an Array
Fetch the results of the first query into an array and loop through it. This approach involves the following steps:
Method 2: Buffering Queries
Configure mysqli to buffer the queries using mysqli_stmt_store_result(). This approach involves the following steps:
Implementation:
For example, to implement Method 2 in your provided code:
... $countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %"; if ($numRecords = $con->prepare($countQuery)) { $numRecords->bind_param("s", $brand); $numRecords->execute(); $numRecords->store_result(); // Buffer the results ... } ...
Additional Notes:
The above is the detailed content of MySQL `Commands Out of Sync` Error: How to Resolve Sequential Query Issues with mysqli?. For more information, please follow other related articles on the PHP Chinese website!