28

I am trying to run the following.

<?php

$db = mysqli_connect("localhost","user","pw") or die("Database error");
mysqli_select_db($db, "database");

$agtid = $_POST['level'];

$sql = sprintf("call agent_hier(%d)", $agtid);

$result = mysqli_query($db, $sql) or exit(mysqli_error($db));

if ($result) {
    echo "<table border='1'>
        <tr><th>id</th>
        <th>name</th>
        <th>parent_id</th>
        <th>parent_name</th>
        <th>level</th>
        <th>email</th></tr>";

    while ($row = mysqli_fetch_assoc($result)) 
    {
        $aid = $row["id"];
        $sql2 = "SELECT * FROM members WHERE MEMNO = '$aid'";
        $result2 = mysqli_query($db,$sql2) or exit(mysqli_error($db));

            while ($newArray = mysqli_fetch_array($result2)) {
                $fname = $newArray['FNAME'];
                $lname = $newArray['LNAME'];
                $mi = $newArray['MI'];  
                $address = $newArray['ADDRESS'];    
                $city = $newArray['CITY'];  
                $state = $newArray['STATE'];    
                $zip = $newArray['ZIP'];
                            $kdate = $newArray['KDATE'];
                $date = abs(strtotime(date('m/d/Y')) - strtotime(date($kdate))) / (60 * 60 * 24);
            }

        echo sprintf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
            $row["id"],$row["name"],
            $row["parent_id"],$row["parent_name"],
            $row["level"],$row["email"]);
    }

    echo "</table>";
}

mysqli_free_result($result);
mysqli_close($db);

?>

If I remove lines from:

  $aid = $row["agent_id"];

to....

  $date = abs(strtotime(date('m/d/Y')) - strtotime(date($kdate))) / (60 * 60 * 24);
  }

everything will work fine. If not, I get the following error:

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

In researching, I think it could be due to multiple MySQLi queries run at the same time, in which using mysqli_multi_query but for all the samples and general data in the guide does not seem to be applicable.

Any ideas?

halfer
  • 19,824
  • 17
  • 99
  • 186
JM4
  • 6,740
  • 18
  • 77
  • 125
  • Where is the line `$date = abs(strtotime(date('m/d/Y')) - strtotime(date($kdate))) / (60 * 60 * 24); }` in your code? You said if you remove up to it, but I can't see it there. – avacariu Sep 02 '10 at 23:43

7 Answers7

43

The MySQL client does not allow you to execute a new query where there are still rows to be fetched from an in-progress query. See Commands out of sync in the MySQL doc on common errors.

You can use mysqli_store_result() to pre-fetch all the rows from the outer query. That will buffer them in the MySQL client, so from the server's point of view your app has fetched the full result set. Then you can execute more queries even in a loop of fetching rows from the now-buffered outer result set.

Or you mysqli_result::fetch_all() which returns the full result set as a PHP array, and then you can loop over that array.

Calling stored procedures is a special case, because a stored procedure has the potential for returning multiple result sets, each of which may have its own set of rows. That's why the answer from @a1ex07 mentions using mysqli_multi_query() and looping until mysqli_next_result() has no more result sets. This is necessary to satisfy the MySQL protocol, even if in your case your stored procedure has a single result set.


PS: By the way, I see you are doing the nested queries because you have data representing a hierarchy. You might want to consider storing the data differently, so you can query it more easily. I did a presentation about this titled Models for Hierarchical Data with SQL and PHP. I also cover this topic in a chapter of my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.


Here is how to implement mysqli_next_result() in CodeIgnitor 3.0.3:

On line 262 of system/database/drivers/mysqli/mysqli_driver.php change

protected function _execute($sql)
{
    return $this->conn_id->query($this->_prep_query($sql));
}

to this

protected function _execute($sql)
{
    $results = $this->conn_id->query($this->_prep_query($sql));
    @mysqli_next_result($this->conn_id); // Fix 'command out of sync' error
    return $results;
}

This has been an issue since 2.x. I just updated to 3.x and had to copy this hack over to the new version.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • Thanks for the great advice. I ended up solving my own question (so far...) in a manner which made more sense on another php page (http://php.net/manual/en/mysqli.store-result.php). Great presentation by the way - i need to give it some real time but seems valuabe. At first glance, however - may be a bum for me since i'm using MySQL - i'm sure similar theories apply – JM4 Sep 03 '10 at 01:05
  • Good answer, helped me to go through a similar problem. Thanks – Victor Jul 31 '13 at 15:07
  • So even if we only have one query using the database object, we should still call `mysqli_next_result()`? – grepsedawk Mar 25 '14 at 05:31
  • Yes, the active query is not "cleared" unless it confirms there are no more result sets to process. – Bill Karwin Mar 25 '14 at 07:16
3

Simply, You have to call mysqli_next_result($db) , after mysqli_free_result is called.

mysqli_free_result($result); mysqli_next_result($db) mysqli_close($db);

Deepan Prabhu Babu
  • 862
  • 11
  • 18
2

simply call this function :

$this->free_result();

function free_result() {
        while (mysqli_more_results($this->conn) && mysqli_next_result($this->conn)) {

            $dummyResult = mysqli_use_result($this->conn);

            if ($dummyResult instanceof mysqli_result) {
                mysqli_free_result($this->conn);
            }
        }
    }
reVerse
  • 35,075
  • 22
  • 89
  • 84
2

You have to close previous connection hold by Stored Procedure. Instead of closing connection each time, you can simply use :

mysqli_next_result($conn);
Salman Mohammad
  • 182
  • 1
  • 14
  • This is the proper answer. – Pacerier May 19 '20 at 04:08
  • @Pacerier - is there any downside to always calling `mysqli_next_result` just before doing each query? Other than the slight smell; ideally I would track down what left the connection in an incomplete state - but then I would call it there, so I'm thinking just always call it, and move on. – ToolmakerSteve Aug 29 '20 at 00:33
0

For new mariaDb check in_predicate_conversion_threshold param. By default you can use up to 1000 attributes for "In" queries

Krios
  • 1
  • 1
-2

If you are also making a few calls to stored procedures, and facing the aforementioned error, I have a solution for you, Mr. Wayne.

IMHO, Somewhere down the line, the CALL to Stored Procedure actually messes up the connection. So all you have to do is reset the database connection handle.

You could even have a function sitting in your config file doing just that for you, and all you do is call that function once before making any query or CALL to the Stored Procedure

My implementation is (just ignore the $app since I am working on silex framework it is there, YMMV)

function flushhandle() {

    global $app;
    global $db_host;
    global $db_user;
    global $db_pass;
    global $db_name;
    $app['mysqlio']->close();
    $app['mysqlio'] = new mysqli($db_host, $db_user, $db_pass, $db_name);
    return $app['mysqlio'];
}
Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
-2

You can do something like this between your first query executes and next query for php mysqli

// check your query
if (@mysqli_multi_query($connect, $sql)) {
    do {
        if ($result = mysqli_store_result($connect)) {
            mysqli_free_result($result);
        }
    } while (mysqli_more_results($connect) && mysqli_next_result($connect));
}
// and now here you can execute another query
  • 1
    Where did you copy this from? – Dharman May 01 '23 at 00:07
  • when we use mysqli_multi_query, this doesn't work syncly, then we have to make the php script wait till the multi query finish, that's why we can wait for results, and after php gets all the results of last query, then we can go for another query, it's simple logic, no need to copy paste.. – ProgrammerJibon May 02 '23 at 01:08