phpcodeigniteractiverecordrows-affected

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?


Solution

  • 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