Sumanth Jois
Sumanth Jois

Reputation: 79

php mysqli command cannot be executed now error

I am trying to update my SQL table with the help of this php code:

$description = "Something about myself";
$insert = $con->prepare("INSERT INTO kys_write (Author, writing , Title , Description , Assets) VALUES (?,?,?,?,?)");
$insert->bind_param("ssssi",$author,$data,$title,$description, $ImageExist);
$insert->execute();

$statement = $con->prepare("SELECT id FROM kys_write WHERE Title=?");
$statement->bind_param("s",$title);
$statement->execute();
$statement->bind_result($lastId);

//Everything works fine if this whole part is removed
$sql = "UPDATE  kys_essentials SET LastId=".$lastId;
if ($con->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $con->error;
}

I am getting a error:

Error updating records:Commands out of sync, you cannot run this command now.

What causes this, and how can I avoid it?

Upvotes: 1

Views: 51

Answers (2)

rhavendc
rhavendc

Reputation: 1013

Fetch your $lastId after the binding and put ' ' for value/s, like this:

//your codes
$statement->bind_result($lastId);

while ($statement->fetch()){
      $sql = "UPDATE kys_essentials SET LastId='".$lastId."'";
      if ($con->query($sql) === TRUE){
        echo "Record updated successfully";
      } else{
          echo "Error updating record: " . $con->error;
      }
}

Upvotes: 0

Saty
Saty

Reputation: 22532

It clear that the result sets of a prepared statement execution need to be fetched completely before executing another prepared statement on the same connection.

You can simplify you code using one query . no use of extra select query

$sql = "UPDATE  kys_essentials SET LastId = (SELECT id FROM kys_write WHERE Title='$Title')";
if ($con->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $con->error;
}

Upvotes: 1

Related Questions