简体   繁体   中英

How to check if the row has been updated?

How to return a boolean if the record has been updated on the database?

Example:

try {
  $SQL = "UPDATE addressbook SET valid = '0' WHERE id = :id";
  $query = $this->db->prepare($SQL);
  $query->bindValue(":id", $id);
  $query->execute();

  //How do I know if record has been updated? 
} catch (PDOException $e) {
  $j['success'] = 'false';
  echo json_encode($j);
  return;
}

You can use:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

PDOStatement::rowCount (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

To your particular case, returning a boolean:

return $query->rowCount() ? true : false;

If something went wrong but your code was updated in the database, that sounds like a really precarious state to be in. It's probably better to use a transaction and rollback on exception.

Something like (untested):

$this->db->beginTransaction();
try {
       $SQL = "UPDATE addressbook SET valid = '0' WHERE id = :id";
      $query = $this->db->prepare($SQL);
      $query->bindValue(":id", $id);
      $query->execute();

      $this->db->commit();

      return true;

      //How do I know if record has been updated? 
} catch (PDOException $e) {
      $this->db->rollback();
      return false;
}

Also, you probably don't want to mix your JSON in with this code, separate it out and have something outside your class deal with JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM