Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if db->update successful with Codeigniter when potentially no rows are updated

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?

like image 288
Voriki Avatar asked Nov 17 '13 12:11

Voriki


People also ask

What does this -> db -> update return?

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.

How do I know if MySQL update query was successful?

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.

What is active record codeigniter?

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.


2 Answers

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

like image 153
user2844810 Avatar answered Sep 19 '22 17:09

user2844810


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; } 
like image 37
s1x Avatar answered Sep 19 '22 17:09

s1x