Question

I am trying to execute my PHP code, which calls two MySQL queries via mysqli, and get the error "Commands out of sync; you can't run this command now".

Here is the code I am using

<?php
$con = mysqli_connect("localhost", "user", "password", "db");
if (!$con) {
    echo "Can't connect to MySQL Server. Errorcode: %s\n". Mysqli_connect_error();
    exit;
}
$con->query("SET NAMES 'utf8'");
$brand ="o";
$countQuery = "SELECT ARTICLE_NO FROM AUCTIONS WHERE upper(ARTICLE_NAME) LIKE % ? %";
if ($numRecords = $con->prepare($countQuery)) {
    $numRecords->bind_param("s", $brand);
    $numRecords->execute();
    $data = $con->query($countQuery) or die(print_r($con->error));
    $rowcount = $data->num_rows;
    $rows = getRowsByArticleSearch("test", "Auctions", " ");
    $last = ceil($rowcount/$page_rows);
}  else {

print_r($con->error);
}
foreach ($rows as $row) {
    $pk = $row['ARTICLE_NO'];
    echo '<tr>' . "\n";
    echo '<td><a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')">'.$row['USERNAME'].'</a></td>' . "\n";
    echo '<td><a href="#" onclick="updateByPk(\'Layer2\', \'' . $pk . '\')">'.$row['shortDate'].'</a></td>' . "\n";
    echo '<td><a href="#" onclick="deleterec(\'Layer2\', \'' . $pk . '\')">DELETE RECORD</a></td>' . "\n";
    echo '</tr>' . "\n";
}
function getRowsByArticleSearch($searchString, $table, $max) {
    $con = mysqli_connect("localhost", "user", "password", "db");
    $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 '%?%' ORDER BY str_to_date(ACCESSSTARTS, '%d/%m/%Y %k:%i:%s')" . $max;
    if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->bind_param("s", $searchString);
        $getRecords->execute();
        $getRecords->bind_result($ARTICLE_NO, $USERNAME, $ACCESSSTARTS, $ARTICLE_NAME, $shortDate);
        while ($getRecords->fetch()) {
            $result = $con->query($recordsQuery);
            $rows = array();
            while($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
            return $rows;
        }
    }
}

I have tried reading up on this, but I am unsure of what to do. I have read about store result and free result, however these have made no difference when using them. I am unsure at exactly which point this error is being caused, and would like to know why it is being caused, and how to fix it.

Going by my debug statements, the first if loop for countQuery is not even being entered, because of an error in my sql syntax near near '% ? %'. However if I just select * instead of trying to limit based on a LIKE clause, I still get the command out of sync error.

Was it helpful?

Solution

You can't have two simultaneous queries because mysqli uses unbuffered queries by default (for prepared statements; it's the opposite for vanilla mysql_query). You can either fetch the first one into an array and loop through that, or tell mysqli to buffer the queries (using $stmt->store_result()).

See here for details.

OTHER TIPS

I solved this problem in my C application - here's how I did it:

  1. Quoting from mysql forums:

    This error results when you terminate your query with a semicolon delimiter inside the application. While it is required to terminate a query with a semicolon delimiter when executing it from the command line or in the query browser, remove the delimiter from the query inside your application.

  2. After running my query and dealing with the results [C API: mysql_store_result()], I iterate over any further potentially pending results that occurs via multiple SQL statement execution such as two or more select statements (back to back without dealing with the results).

    The fact is that my procedures don't return multiple results but the database doesn't know that until I execute: [C API: mysql_next_result()]. I do this in a loop (for good measure) until it returns non-zero. That's when the current connection handler knows it's okay to execute another query (I cache my handlers to minimize connection overhead).

    This is the loop I use:

    for(; mysql_next_result(mysql_handler) == 0;) 
      /* do nothing */;
    

I don't know PHP but I'm sure it has something similar.

I had today the same problem, but only when working with a stored procedure. This make the query behave like a multi query, so you need to "consume" other results available before make another query.

while($this->mysql->more_results()){
    $this->mysql->next_result();
    $this->mysql->use_result();
}

I call this function every time before using $mysqli->query Works with stored procedures as well.

function clearStoredResults(){
    global $mysqli;

    do {
         if ($res = $mysqli->store_result()) {
           $res->free();
         }
        } while ($mysqli->more_results() && $mysqli->next_result());        

}

I use CodeIgniter. One server OK ... this one probably older ... Anyway using

$this->db->reconnect();

Fixed it.

The problem is the MySQL client C library, which most MySQL APIs are built on. The problem is that the C library doesn't support simultaneous execution of queries, so all APIs built on top of that also do not. Even if you use unbuffered queries. This is one reason why the asynchronous MySQL API was written. It communicates directly with the MySQL server using TCP and the wire-protocol does support simultaneous queries.

Your solution is to either modify the algorithm so you don't need to have both in progress at once, or change them to use buffered queries, which is probably one of the original reasons for their existence in the C library (the other is to provide a kind of cursor).

to solve this problem you have to store result data before use it

$numRecords->execute();

$numRecords->store_result();

that's all

For those that the previous answers didn't help... here is what was MY PROBLEM!!!

the param binding was "dynamic" so I had a variable that sets the params of the data in order to use bind_param. So that variable was wrong but instead of throwing an error like "wrong param data" it says "out of sync bla bla bla" so I was confused...

I hope it helped someone!

Once you used

stmt->execute();

You must close it to use another query.

stmt->close();

This problem was hunting me for hours. Hopefully, it will fix yours.

I think the problem is that you're making a new connection in the function, and then not closing it at the end. Why don't you try passing in the existing connection and re-using it?

Another possibility is that you're returning out of the middle of a while loop fetching. You never complete that outer fetch.

Check to see if you are typing all the parameters correctly. It throws the same error if the amount of parameters defined and then passed to the function are different.

This is not related to the original question, but i had the same error-message and this thread is the first hit in Google and it took me a while to figure out what the Problem was, so it May be of use for others:

i'm NOT using mysqli, still using mysql_connect i had some simple querys, but ONE query caused all other querys to fail within the same Connection.

I use mysql 5.7 and php 5.6 i had a table with the data-Type "JSON". obviously, my php-version did not recognize the return value from mysql (php just did not know what to do with the JSON-Format because the built-in mysql-module was too old (at least i think))

for now i changed the JSON-Field-Type to Text (as for now i don't need the native mysql JSON-functionality) and everything works fine

If you either use Buffered or Unbuffered result set for fetching data, first you must simply clear the fetched data from the memory, once you have fetched all the data. As you can't execute another MYSQL procedure on the same connection till you clear the fetched memory. Add this below function right end of your script, so it will solve the problem

$numRecords->close(); or $numRecords->free(); // This clears the referencing memory, and will be ready for the next MYSQL fetch

Reference from the PHP documentation

I ran into this error using Doctrine DBAL QueryBuilder.

I created a query with QueryBuilder that uses column subselects, also created with QueryBuilder. The subselects were only created via $queryBuilder->getSQL() and not executed. The error happened on creating the second subselect. By provisionally executing each subselect with $queryBuilder->execute() before using $queryBuilder->getSQL(), everything worked. It is as if the connection $queryBuilder->connection remains in an invalid state for creating a new SQL before executing the currently prepared SQL, despite the new QueryBuilder instance on each subselect.

My solution was to write the subselects without QueryBuilder.

My problem was that I was using first prepare statement and then I was using mysqli query on the same page and was getting the error "Commands out of sync; you can't run this command now". The error was only then when I was using the code that had prepare statement.

What I did was to close the question. and it worked.

mysqli_stmt_close($stmt);

My code

get_category.php (here using prepare statement )

    <?php


    global $connection;
    $cat_to_delete =    mysqli_real_escape_string($connection, $_GET['get'] );

    $sql = "SELECT category_name FROM categories WHERE category_id = ? ;";


    $stmt = mysqli_stmt_init($connection);

    if (!mysqli_stmt_prepare($stmt, $sql))
        $_SESSION['error'] = "Error at preaparing for deleting query. mysqli_stmt_error($stmt) ." & redirect('../error.php');

    mysqli_stmt_bind_param($stmt, 's', $cat_to_delete);

    if (!mysqli_stmt_execute($stmt))
        $_SESSION['error'] = "ERror at executing delete category ".mysqli_stmt_error($stmt) &
            redirect('../error.php');


    mysqli_stmt_bind_result($stmt, $cat_name);

    if (!mysqli_stmt_fetch($stmt)) {
        mysqli_stmt_error($stmt);
    }



    mysqli_stmt_free_result($stmt);
    mysqli_stmt_close($stmt);

admin_get_category_body.php (here mysqli)

        <?php

        if (isset($_GET['get']) && !empty($_GET['get']) )
        {
            include 'intodb/edit_category.php';
        }


        if (check_method('get') && isset($_GET['delete']) )
        {
            require 'intodb/delete_category.php';
        }


        if (check_method('get') && isset($_GET['get']) )
        {
            require 'intodb/get_category.php';
        }


        ?>

        <!--            start: cat body          -->

        <div     class="columns is-mobile is-centered is-vcentered">
            <div class="column is-half">
                <div   class="section has-background-white-ter box ">


                    <div class="has-text-centered column    " >
                        <h4 class="title is-4">Ctegories</h4>
                    </div>

                    <div class="column " >


                        <?php if (check_method('get') && isset($_GET['get'])) {?>
                        <form action="" method="post">
                            <?php } else {?>
                            <form action="intodb/add_category.php" method="post">
                                <?php } ?>

                                <label class="label" for="admin_add_category_bar">Add Category</label>
                                <div class="field is-grouped">

                                    <p class="control is-expanded">

                                        <?php if (check_method('get') && isset($_GET['get'])) {?>

                                            <input id="admin_add_category_bar" name="admin_add_category_bar_edit" class="input" type="text" placeholder="Add Your Category Here" value="<?php echo $cat_name; ?>">

                                            <?php


                                            ?>
                                        <?php } else {?>
                                            <input id="admin_add_category_bar" name="admin_add_category_bar" class="input" type="text" placeholder="Add Your Category Here">

                                        <?php } ?>
                                    </p>
                                    <p class="control">
                                        <input type="submit" name="admin_add_category_submit" class="button is-info my_fucking_hover_right_arrow" value="Add Category">
                                    </p>
                                </div>
                            </form>


                            <div class="">

                                <!--            start: body for all posts inside admin          -->


                                <table class="table is-bordered">
                                    <thead>
                                    <tr>
                                        <th><p>Category Name</p></th>
                                        <th><p>Edit</p></th>
                                        <th><p>Delete</p></th>
                                    </tr>
                                    </thead>

                                    <?php

                                    global $connection;
                                    $sql = "SELECT * FROM categories ;";

                                    $result = mysqli_query($connection, $sql);
                                    if (!$result) {
                                        echo mysqli_error($connection);
                                    }
                                    while($row = mysqli_fetch_assoc($result))
                                    {
                                        ?>
                                        <tbody>
                                        <tr>
                                            <td><p><?php echo $row['category_name']?></p></td>
                                            <td>
                                                <a href="admin_category.php?get=<?php echo $row['category_id']; ?>" class="button is-info my_fucking_hover_right_arrow" >Edit</a>

                                            </td>

                                            <td>
                                                <a href="admin_category.php?delete=<?php echo $row['category_id']; ?>" class="button is-danger my_fucking_hover_right_arrow" >Delete</a>

                                            </td>
                                        </tr>


                                        </tbody>
                                    <?php }?>
                                </table>

                                <!--           end: body for all posts inside admin             -->




                            </div>

                    </div>
                </div>


            </div>

        </div>
        </div>

Something that just crossed my mind, I am also again adding connection variable via global $connection;. So I think basically a whole new set of query system is being started after ending of prepare statement with mysqli_stmt_close($stmt); and also I am adding these files and other stuff via include

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top