I've been using $this->db->affected_rows()
to check if updates have been successful. But this doesn't work when a user inputs the same data to be stored that is already stored (because no column is actually updated). My workaround has been to get the stored data, compare to the inputted data, update if different, return a NO_CHANGE constant if same. With JSON data, there's an extra parsing step.
Is there an easier way to check that there was no error with the update? As in, something that doesn't require getting the stored data beforehand?
You can use $this->db->affected_rows() in Codeigniter this returns a numeric value when doing "write" type queries (insert, update, etc.). In MySQL DELETE FROM TABLE returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows.
Use if(mysqli_affected_rows($mysqli) >0 ) or no comparison at all. Sidenote: ==1 is only comparing for 1, as opposed to >0 which you may be trying to update more than one row.
Active Record Class CodeIgniter uses a modified version of the Active Record Database Pattern. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action.
If I understand correctly, you can use transactions to ensure that there was no error with the update:
$this->db->trans_start(); $this->db->query('AN SQL QUERY...'); $this->db->update('table',$array); $this->db->trans_complete(); if ($this->db->trans_status() === FALSE) { // generate an error... or use the log_message() function to log your error }
Just remember this only validates that there were no SQL errors during all the queries inside the transaction.
Here's the link for more info Code Igniter Active Record Transaction
Additionaly to the accepted answer solution you could expand the code like the following to differentiate affected_rows
and trans_status
results/errors.
$this->db->trans_start(); $this->db->query('AN SQL QUERY...'); $this->db->update('table',$array); $this->db->trans_complete(); // was there any update or error? if ($this->db->affected_rows() == '1') { return TRUE; } else { // any trans error? if ($this->db->trans_status() === FALSE) { return false; } return true; }
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