How can the error "Commands out of sync; you can't run this command now" be resolved when using mysqli_query in PHP?

When using mysqli_query in PHP, the error "Commands out of sync; you can't run this command now" typically occurs when multiple queries are executed without fetching the results of the previous query. To resolve this issue, you need to ensure that you fetch the results of each query before executing the next one. This can be done by using mysqli_store_result or mysqli_free_result after each query execution.

// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Execute the first query
$result1 = mysqli_query($connection, "SELECT * FROM table1");

// Fetch the results of the first query
mysqli_store_result($connection);

// Execute the second query
$result2 = mysqli_query($connection, "SELECT * FROM table2");

// Fetch the results of the second query
mysqli_store_result($connection);

// Close the connection
mysqli_close($connection);