"Commands Out of Sync" Error in MySQLi: A Comprehensive Explanation
MySQLi throws the "Commands out of sync" error when a new query is attempted while there are still unread rows from a previous query.
Reason for the Error
The MySQL client protocol requires that all results from a query be fetched before a new query can be executed. This ensures consistency in handling result sets and prevents data loss.
Solutions
mysqli_store_result() or mysqli_result::fetch_all():
Prefetch all the rows from the outer query using mysqli_store_result() or fetch the entire result set as an array using mysqli_result::fetch_all(). This buffers the results in the client, allowing multiple queries to be executed.
Stored Procedures and mysqli_multi_query():
Stored procedures can return multiple result sets. To handle this, use mysqli_multi_query() and iterate through the results using mysqli_next_result() until all result sets are processed.
Code Snippet
Here's a modified version of the code from the question, using mysqli_store_result():
$result = mysqli_query($db, $sql) or exit(mysqli_error($db)); if ($result) { $result->store_result(); // Buffer the result set echo "<table border='1'> <tr><th>id</th> <th>name</th> <th>parent_id</th> <th>parent_name</th> <th>level</th> <th>email</th></tr>"; while ($row = mysqli_fetch_assoc($result)) { $aid = $row["id"]; $sql2 = "SELECT * FROM members WHERE MEMNO = '$aid'"; $result2 = mysqli_query($db, $sql2) or exit(mysqli_error($db)); if ($result = mysqli_fetch_assoc($result2)) { $fname = $ newArray['FNAME']; $lname = $newArray['LNAME']; $mi = $newArray['MI']; $address = $newArray['ADDRESS']; $city = $newArray['CITY']; $state = $newArray['STATE']; $zip = $newArray['ZIP']; $kdate = $newArray['KDATE']; $date = abs(strtotime(date('m/d/Y')) - strtotime(date($kdate))) / (60 * 60 * 24); } echo sprintf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $row["id"],$row["name"], $row["parent_id"],$row["parent_name"], $row["level"],$row["email"]); } echo "</table>"; } mysqli_free_result($result); mysqli_close($db);
Possible Design Improvement
Storing hierarchical data in a relational database can lead to complex queries. Consider using alternative models, such as nested sets or adjacency lists, to simplify data storage and retrieval.
The above is the detailed content of How to Resolve the MySQLi 'Commands Out of Sync' Error?. For more information, please follow other related articles on the PHP Chinese website!