Commands out of sync; you can't run this command now

Commands out of sync; you can't run this command now

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Commands out of sync; you can't run this command now

The error message "Commands out of sync; you can't run this command now" is one of the most confusing errors in the PHP mysqli extension. It often appears when developers assume that executing a prepared statement automatically returns a result set that they can immediately iterate over or query again. In reality, the state of the connection and the specific API method used to fetch data are strictly enforced.

In your specific case, the root cause is located within the getRowsByArticleSearch function. You have created a scenario where you prepare a statement, execute it, and then attempt to run an unprepared query() on the same connection object while a result resource is still active from the prepared statement.

Here is the problematic sequence in your code:

if ($getRecords = $con->prepare($recordsQuery)) {
    $getRecords->bind_param("s", $searchString);
    $getRecords->execute();
    
    // CRITICAL ERROR HERE
    $result = $con->query($recordsQuery); 
}

When you call $getRecords->execute(), the MySQL server generates a result set for that prepared statement. However, you are not retrieving it via the mysqli_stmt object ($getRecords). Instead, you immediately switch to using the connection object ($con) and calling query($recordsQuery) again with the same SQL string.

At this exact moment, there is an active result set associated with $getRecords. The MySQL driver maintains a "current command" flag. Because the previous command (the executed prepared statement) has not been fully consumed or explicitly freed, the driver refuses to accept a new command via query(). This results in the "Commands out of sync" error.

The Correct Approach: Using the Statement Object

The fix is straightforward: you must retrieve the result set from the statement object that was executed, not by issuing a new query on the connection. You should use $getRecords->get_result() (available in PHP 5.5+ with MYSQLI_USE_RESULT) or iterate using mysqli_stmt_store_result().

Here is how the corrected function should look:

function getRowsByArticleSearch($searchString, $table, $max) {
    // Note: Ensure you don't pass $max inside the SQL string directly if it contains variables.
    // It looks like $max was intended as a limit clause parameter or logic error.
    
    $con = mysqli_connect("localhost", "user", "password", "db");
    if (!$con) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $recordsQuery = "SELECT ARTICLE_NO, USERNAME, ACCESSSTARTS, ARTICLE_NAME, 
                      date_format(str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s'), '%d %m %Y') AS shortDate 
                      FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE CONCAT('%', ?, '%')";

    if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        
        // Execute the prepared statement
        $getRecords->execute();

        // Retrieve the result set from the statement object
        $result = $getRecords->get_result(); 

        $rows = [];
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        
        return $rows;
    } else {
        print_r($con->error);
    }
}

Why This Happens: The Sync Flag

The mysqli driver tracks the state of the last command executed on a connection. If you execute a prepared statement and do not fetch its results, the connection is in a specific state. Attempting to run a standard query() while the previous result is unfetched triggers this synchronization check and fails.

You mentioned trying store_result and free_result. These functions are valid but require careful handling:

  • mysqli_stmt_store_result($stmt): Forces the driver to retrieve all rows from the server immediately into memory. If you forget to call this before checking for errors or running another command, you might get sync errors later. However, simply calling get_result() implicitly handles the storage of the result set in newer drivers.
  • mysqli_stmt_free_result($stmt): Frees the memory allocated for the result set. This is useful if you are processing a massive dataset and want to free memory before running the next heavy query.

In your original code, calling $con->query() inside the loop (or even outside) while $getRecords holds an active result was the fatal flaw. The driver could not know which result set belonged to which command without explicit retrieval.

Additional Observations

There are other significant issues in the provided snippet that will cause runtime errors or security vulnerabilities if deployed:

  1. SQL Injection Risk: In the countQuery and getRowsByArticleSearch, you used placeholders (?) but then attempted to concatenate $max directly into the SQL string using string concatenation (. $max). If $max is a variable, this bypasses prepared statement protection entirely for that part of the query. Always bind parameters or use literal values for things like LIMIT clauses.
  2. Syntax Error: The placeholder usage in your original code was '% ? %'. PHP's MySQLi driver does not support the %?% syntax directly inside a prepared statement string; you must concatenate the wildcards with the bound parameter, e.g., "LIKE CONCAT('%', ?, '%')" or "WHERE name LIKE '%' || ? || '%' ".
  3. Resource Management: Always ensure connections are closed (mysqli_close($con)) after use to prevent resource exhaustion in long-running scripts.

By ensuring that every execute() call is immediately followed by a corresponding fetch operation on the same statement object, and avoiding mixing query() and prepare() on the same connection without clearing previous results, you will resolve the synchronization error.

Our network