Skip to content
PHP Logo

What are the best practices for using prepared statements in PHP to avoid errors like "Commands out of sync"?

When using prepared statements in PHP, it's important to always close any open result sets before executing a new query to avoid errors like "Commands out of sync". To solve this issue, make sure to call `mysqli_stmt::close()` after fetching results from a prepared statement to free up resources before executing another query.

php
$stmt = $mysqli->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($id, $name);

while ($stmt->fetch()) {
    // Process results
}

$stmt->close(); // Close the statement before executing another query