Reputation: 10828
How to return a boolean if the record has been updated on the database?
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
Reputation: 8472
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)
return $query->rowCount() ? true : false;
Upvotes: 42
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