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; }
One way is to start a transaction, select the contents of the row and compare it to what you're going to update it to. If they don't match, then do the update and end the transaction. If they match, rollback the transaction.
If you want to know when a row is inserted, the easiest thing would be to simply add a date or timestamp field with a default value (like getDate()) that automatically fills in the date/time when the row is inserted.
To get the last updated record in SQL Server: We can write trigger (which automatically fires) i.e. whenever there is a change (update) that occurs on a row, the “lastupdatedby” column value should get updated by the current timestamp.
SQL UPDATE Syntax To use the UPDATE method, you first determine which table you need to update with UPDATE table_name . After that, you write what kind of change you want to make to the record with the SET statement. Finally, you use a WHERE clause to select which records to change.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With