1

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?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Sumanth Jois
  • 79
  • 1
  • 10
  • Possible duplicate of [PHP Commands Out of Sync error](http://stackoverflow.com/questions/14554517/php-commands-out-of-sync-error) – e4c5 May 03 '16 at 08:09
  • Possible duplicate of [Commands out of sync; you can't run this command now](http://stackoverflow.com/questions/614671/commands-out-of-sync-you-cant-run-this-command-now) – Ruslan Osmanov May 03 '16 at 08:09
  • i have seen both of the above but it dint help! – Sumanth Jois May 03 '16 at 08:14

2 Answers2

1

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;
}
Saty
  • 22,443
  • 7
  • 33
  • 51
0

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;
      }
}
rhavendc
  • 985
  • 8
  • 21