What are the best practices for debugging PHP MySQLi queries that result in "commands out of sync" errors?

When encountering "commands out of sync" errors in PHP MySQLi queries, it typically means that there are multiple active queries on the same connection that have not been properly fetched or closed. To solve this issue, ensure that you properly fetch and free the result set before executing another query on the same connection.

// Example of properly fetching and freeing result sets to avoid "commands out of sync" errors

// Perform first query
$result1 = $mysqli->query("SELECT * FROM table1");

// Fetch and process result set
while ($row = $result1->fetch_assoc()) {
    // Process data
}

// Free result set
$result1->free();

// Perform second query
$result2 = $mysqli->query("SELECT * FROM table2");

// Fetch and process result set
while ($row = $result2->fetch_assoc()) {
    // Process data
}

// Free result set
$result2->free();