Returning information from MySQL using php - php

I'm currently trying to get into php and MySQL and i'm using this little project as a learning curve, but I've hit a bump that I can't get through. I have the following code that is accessing my MySQL database and I am currently trying to echo the data out using the following search function:
<?php
ob_start();
require("config.php");
ob_end_clean();
$req=$_REQUEST['workingDate'];
$req2=$_REQUEST['location'];
mysql_connect("XXXXXXXXXXX",$username,$password);
mysql_select_db($database) or die( "Unable to select database");
if ($req!="all" && $req2!="all") $query="SELECT * FROM TrackerTable WHERE workingDate='$req' AND location1='$req2'";
else if($req=="all" && $req2!="all" ) $query="SELECT * FROM TrackerTable WHERE location1='$req2'";
else if($req!="all" && $req2=="all" ) $query="SELECT * FROM TrackerTable WHERE make='$req'";
else if($req=="all" || $req2=="all" ) $query="SELECT * FROM TrackerTable";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_query($result);
mysql_close();
$i=0;
for ($i; $i < $num; $i++){
$f12=mysql_result($result,$i,"workingDate");
$f13=mysql_result($result,$i,"location1");
echo $f12." ".$f13."<br />";
}
?>
The problem I have is that whenever I try to search the database using the following html form:
<form method="post" action="searchFunction.php" name="input" id="searchform">
<label class="section">Search Options</label><br />
<input name="workingDate" type="text" id="workingDate" placeholder="Search by Date">
<input name="location1" type="text" id="location1" placeholder="Search by Location">
<input name="submit" type="submit" id="add" value="Find!">
</form>
I get this error thrown at me:
Warning: mysql_query() expects parameter 1 to be string, resource given in /XXXXXX/XXXXXX/XXXXX/XXXX/XXXXX.com/XXXXXX/searchFunction.php on line 20
I have no idea what could be causing the problem as it all seems fairly in place to me. Is there an obvious mistake i'm making or is it all just completely messed up? I've been looking at it that long that I can't tell what makes sense anymore!
Any help would be greatly appreciated. Thanks guys!

You are sure that variable $query is defined?
This because in the statement if/elseif is where you define the variable $query.
// first define default value for your $query variable
$query="SELECT * FROM TrackerTable";
// then use your if/else statement
if ($req!="all" && $req2!="all") .....................
You have an error
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_query($result); // error here
mysql_close();
$result is not a string, is resource.
mysql_query($result);
Check http://php.net/manual/en/function.mysql-query.php for details

You're trying to run your query twice:
$result=mysql_query($query);
^^^^^^--- your SQL
mysql_query($result);
^^^^^^^---- result handle (aka resource) from previous call
The second query call is utterly irrelevant/useless. You're passing in the wrong argument to the call, and you're not capturing the return value from the query anyways. Even if it was running properly, you're throwing away the query results.
You then close your DB connection, so when you try to call mysql_result() later on, there's no more DB connection to fetch your results from.
And on top of all this, you're vulnerable to sql injection attacks.
In short, this code is a total disaster.

Related

Delete from mysql after select in php [duplicate]

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>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>DELETE RECORD</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.
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.
I solved this problem in my C application - here's how I did it:
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.
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, and it 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());
}
Once you used
stmt->execute();
You MAY close it to use another query.
stmt->close();
This problem was hunting me for hours. Hopefully, it will fix yours.
I use CodeIgniter.
One server OK ... this one probably older ...
Anyway using
$this->db->reconnect();
Fixed it.
to solve this problem you have to store result data before use it
$numRecords->execute();
$numRecords->store_result();
that's all
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).
Another cause: store_result() cannot be called twice.
For instance, in the following code, Error 5 is printed.
<?php
$db = new mysqli("localhost", "something", "something", "something");
$stmt = $db->stmt_init();
if ($stmt->error) printf("Error 1 : %s\n", $stmt->error);
$stmt->prepare("select 1");
if ($stmt->error) printf("Error 2 : %s\n", $stmt->error);
$stmt->execute();
if ($stmt->error) printf("Error 3 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 4 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 5 : %s\n", $stmt->error);
(This may not be relevant to the original sample code, but it can be relevant to people seeking answers to this error.)
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 put this line of code after I was done collecting the results of the first query. Worked for me
mysqli_next_result($connection);
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
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.
I am using ODBC, and this fix works for me:
ODBC -> tab System DSN -> double click to configure my data source -> details -> tab Cursors -> Uncheck [Don't cache results of forward-only cursors] -> click Ok
I often hit this error and it's always when I run a stored procedure that I have been debugging in phpmyadmin or SQL Workbench (I am working in php connecting with mysqli).
The error results from the fact that the debugging involves inserting SELECT statements at strategic points in the code to tell me the state of variables, etc. Running a stored procedure that produces multiple results sets in these client environments is fine, but it produces the "Commands out of sync" error when called from php. The solution is always to comment-out or remove the debugging selects so the procedure has only one result set.
Just for reference i had this problem mixing both multi_query and query in the same code:
$connection->multi_query($query);
...
$connection->query($otherQuery);
Which for what i read had unconsumed results pending, therefore causing in the mentioned error.
I solved it with a loop consuming all the results of the multi_query:
$connection->multi_query($query);
while ($connection->next_result()); // <--- solves the problem
...
$connection->query($otherQuery);
In my case all the queries in the multi_query where inserts so i had no interest in the results themselves.
To clear the referencing memory, and run the next MYSQL fetch
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 until 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
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
This is an old question, but none of the posted answers worked in my case, I found that in my case I had selects and updates on a table in my stored procedure, the same table had an update trigger which was being triggered and senging the procedure into an infinite loop. Once the bug was found the error went away.
The definitive solution for this error is the following:
1) You must copy and paste this code above the next query to the stored procedure.
do if($result=mysqli_store_result($myconnection)){ mysqli_free_result($result); } while(mysqli_more_results($myconnection) && mysqli_next_result($myconnection));
Create two connections, use both separately
$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");
$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS");

php mysql Commands out of sync; you can't run this command now [duplicate]

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>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>DELETE RECORD</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.
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.
I solved this problem in my C application - here's how I did it:
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.
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, and it 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());
}
Once you used
stmt->execute();
You MAY close it to use another query.
stmt->close();
This problem was hunting me for hours. Hopefully, it will fix yours.
I use CodeIgniter.
One server OK ... this one probably older ...
Anyway using
$this->db->reconnect();
Fixed it.
to solve this problem you have to store result data before use it
$numRecords->execute();
$numRecords->store_result();
that's all
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).
Another cause: store_result() cannot be called twice.
For instance, in the following code, Error 5 is printed.
<?php
$db = new mysqli("localhost", "something", "something", "something");
$stmt = $db->stmt_init();
if ($stmt->error) printf("Error 1 : %s\n", $stmt->error);
$stmt->prepare("select 1");
if ($stmt->error) printf("Error 2 : %s\n", $stmt->error);
$stmt->execute();
if ($stmt->error) printf("Error 3 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 4 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 5 : %s\n", $stmt->error);
(This may not be relevant to the original sample code, but it can be relevant to people seeking answers to this error.)
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 put this line of code after I was done collecting the results of the first query. Worked for me
mysqli_next_result($connection);
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
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.
I am using ODBC, and this fix works for me:
ODBC -> tab System DSN -> double click to configure my data source -> details -> tab Cursors -> Uncheck [Don't cache results of forward-only cursors] -> click Ok
I often hit this error and it's always when I run a stored procedure that I have been debugging in phpmyadmin or SQL Workbench (I am working in php connecting with mysqli).
The error results from the fact that the debugging involves inserting SELECT statements at strategic points in the code to tell me the state of variables, etc. Running a stored procedure that produces multiple results sets in these client environments is fine, but it produces the "Commands out of sync" error when called from php. The solution is always to comment-out or remove the debugging selects so the procedure has only one result set.
Just for reference i had this problem mixing both multi_query and query in the same code:
$connection->multi_query($query);
...
$connection->query($otherQuery);
Which for what i read had unconsumed results pending, therefore causing in the mentioned error.
I solved it with a loop consuming all the results of the multi_query:
$connection->multi_query($query);
while ($connection->next_result()); // <--- solves the problem
...
$connection->query($otherQuery);
In my case all the queries in the multi_query where inserts so i had no interest in the results themselves.
To clear the referencing memory, and run the next MYSQL fetch
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 until 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
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
This is an old question, but none of the posted answers worked in my case, I found that in my case I had selects and updates on a table in my stored procedure, the same table had an update trigger which was being triggered and senging the procedure into an infinite loop. Once the bug was found the error went away.
The definitive solution for this error is the following:
1) You must copy and paste this code above the next query to the stored procedure.
do if($result=mysqli_store_result($myconnection)){ mysqli_free_result($result); } while(mysqli_more_results($myconnection) && mysqli_next_result($myconnection));
Create two connections, use both separately
$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");
$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS");

PHP num_rows and fetch_assoc in the same statement [duplicate]

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>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>DELETE RECORD</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.
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.
I solved this problem in my C application - here's how I did it:
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.
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, and it 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());
}
Once you used
stmt->execute();
You MAY close it to use another query.
stmt->close();
This problem was hunting me for hours. Hopefully, it will fix yours.
I use CodeIgniter.
One server OK ... this one probably older ...
Anyway using
$this->db->reconnect();
Fixed it.
to solve this problem you have to store result data before use it
$numRecords->execute();
$numRecords->store_result();
that's all
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).
Another cause: store_result() cannot be called twice.
For instance, in the following code, Error 5 is printed.
<?php
$db = new mysqli("localhost", "something", "something", "something");
$stmt = $db->stmt_init();
if ($stmt->error) printf("Error 1 : %s\n", $stmt->error);
$stmt->prepare("select 1");
if ($stmt->error) printf("Error 2 : %s\n", $stmt->error);
$stmt->execute();
if ($stmt->error) printf("Error 3 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 4 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 5 : %s\n", $stmt->error);
(This may not be relevant to the original sample code, but it can be relevant to people seeking answers to this error.)
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 put this line of code after I was done collecting the results of the first query. Worked for me
mysqli_next_result($connection);
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
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.
I am using ODBC, and this fix works for me:
ODBC -> tab System DSN -> double click to configure my data source -> details -> tab Cursors -> Uncheck [Don't cache results of forward-only cursors] -> click Ok
I often hit this error and it's always when I run a stored procedure that I have been debugging in phpmyadmin or SQL Workbench (I am working in php connecting with mysqli).
The error results from the fact that the debugging involves inserting SELECT statements at strategic points in the code to tell me the state of variables, etc. Running a stored procedure that produces multiple results sets in these client environments is fine, but it produces the "Commands out of sync" error when called from php. The solution is always to comment-out or remove the debugging selects so the procedure has only one result set.
Just for reference i had this problem mixing both multi_query and query in the same code:
$connection->multi_query($query);
...
$connection->query($otherQuery);
Which for what i read had unconsumed results pending, therefore causing in the mentioned error.
I solved it with a loop consuming all the results of the multi_query:
$connection->multi_query($query);
while ($connection->next_result()); // <--- solves the problem
...
$connection->query($otherQuery);
In my case all the queries in the multi_query where inserts so i had no interest in the results themselves.
To clear the referencing memory, and run the next MYSQL fetch
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 until 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
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
This is an old question, but none of the posted answers worked in my case, I found that in my case I had selects and updates on a table in my stored procedure, the same table had an update trigger which was being triggered and senging the procedure into an infinite loop. Once the bug was found the error went away.
The definitive solution for this error is the following:
1) You must copy and paste this code above the next query to the stored procedure.
do if($result=mysqli_store_result($myconnection)){ mysqli_free_result($result); } while(mysqli_more_results($myconnection) && mysqli_next_result($myconnection));
Create two connections, use both separately
$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");
$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS");

Getting error when trying to fetch data from MySQL using PHP

When trying to fetch data from a Mysql database using PHP, the following code gets a message:
Getting error:
undefined variable result.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
echo <<<_END
<form action="fetchdata.php" method="post"><pre>
Enter Country <input type="text" name="field">
<input type="submit" value="Display Records">
</pre></form>
_END;
if (isset($_POST['field'])) {
$field=$_post($conn,'field');
$query="SELECT * FROM customers WHERE Country = '$field'";
$result=$conn->query($query);
if (!$result) die($conn->error);
}
$rows = $result->num_rows;
Instead of
$field=$_post($conn,'field');
Maybe you mean
$field=$_POST['field'];
Additionally you use $result at the end, even when it is not defined:
$rows = $result->num_rows;
Also you never output any data and print it. You just store it in variables.
In any case: What you are doing there by writing form data directly into a query string, is dangerous. I recommend you to use PDO together with Named Parameters. Also maybe read up about SQL injections.
Here is another stackoverflow question with a nice answer, regarding SQL injections. It includes both PDO and mysqli: https://stackoverflow.com/a/60496/6637731
Without telling how request to this code is done, one guess is that isset($_POST['field']) returns false, hence variable $result is never defined but you use it anyway below in $result->num_rows.
You made a mistake in the below line. It should be
$field=$_POST['field'];
not
$field=$_post($conn,'field');

How to make query inside fetching data from another query [duplicate]

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>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>DELETE RECORD</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.
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.
I solved this problem in my C application - here's how I did it:
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.
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, and it 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());
}
Once you used
stmt->execute();
You MAY close it to use another query.
stmt->close();
This problem was hunting me for hours. Hopefully, it will fix yours.
I use CodeIgniter.
One server OK ... this one probably older ...
Anyway using
$this->db->reconnect();
Fixed it.
to solve this problem you have to store result data before use it
$numRecords->execute();
$numRecords->store_result();
that's all
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).
Another cause: store_result() cannot be called twice.
For instance, in the following code, Error 5 is printed.
<?php
$db = new mysqli("localhost", "something", "something", "something");
$stmt = $db->stmt_init();
if ($stmt->error) printf("Error 1 : %s\n", $stmt->error);
$stmt->prepare("select 1");
if ($stmt->error) printf("Error 2 : %s\n", $stmt->error);
$stmt->execute();
if ($stmt->error) printf("Error 3 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 4 : %s\n", $stmt->error);
$stmt->store_result();
if ($stmt->error) printf("Error 5 : %s\n", $stmt->error);
(This may not be relevant to the original sample code, but it can be relevant to people seeking answers to this error.)
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 put this line of code after I was done collecting the results of the first query. Worked for me
mysqli_next_result($connection);
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
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.
I am using ODBC, and this fix works for me:
ODBC -> tab System DSN -> double click to configure my data source -> details -> tab Cursors -> Uncheck [Don't cache results of forward-only cursors] -> click Ok
I often hit this error and it's always when I run a stored procedure that I have been debugging in phpmyadmin or SQL Workbench (I am working in php connecting with mysqli).
The error results from the fact that the debugging involves inserting SELECT statements at strategic points in the code to tell me the state of variables, etc. Running a stored procedure that produces multiple results sets in these client environments is fine, but it produces the "Commands out of sync" error when called from php. The solution is always to comment-out or remove the debugging selects so the procedure has only one result set.
Just for reference i had this problem mixing both multi_query and query in the same code:
$connection->multi_query($query);
...
$connection->query($otherQuery);
Which for what i read had unconsumed results pending, therefore causing in the mentioned error.
I solved it with a loop consuming all the results of the multi_query:
$connection->multi_query($query);
while ($connection->next_result()); // <--- solves the problem
...
$connection->query($otherQuery);
In my case all the queries in the multi_query where inserts so i had no interest in the results themselves.
To clear the referencing memory, and run the next MYSQL fetch
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 until 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
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
This is an old question, but none of the posted answers worked in my case, I found that in my case I had selects and updates on a table in my stored procedure, the same table had an update trigger which was being triggered and senging the procedure into an infinite loop. Once the bug was found the error went away.
The definitive solution for this error is the following:
1) You must copy and paste this code above the next query to the stored procedure.
do if($result=mysqli_store_result($myconnection)){ mysqli_free_result($result); } while(mysqli_more_results($myconnection) && mysqli_next_result($myconnection));
Create two connections, use both separately
$mysqli = new mysqli("localhost", "Admin", "dilhdk", "SMS");
$conn = new mysqli("localhost", "Admin", "dilhdk", "SMS");

Categories