I'll-Be-Back
I'll-Be-Back

Reputation: 10828

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;
}

Upvotes: 22

Views: 22026

Answers (2)

CD001
CD001

Reputation: 8472

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;

Upvotes: 42

Levi Morrison
Levi Morrison

Reputation: 19552

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.

Upvotes: 1

Related Questions