Finding the number of affected rows

Finding the number of affected rows can be useful in several ways—perhaps you want to update some records and only proceed if a certain number of records are updated, or perhaps you simply want to display the number of rows that have been deleted or updated by a query.

How to do it...

  1. Add or adapt the following code into your model:
      function update($id, $data) {
        $this->db->where('id', $id); 
        if ($data->db->update($data, 'table_name')) {
          return $this->db->affected_rows(); 
        } else { 
          return false; 
        } 
      } 

How it works...

The model function update() accepts two parameters: a $data array and the $id array of the database row we wish to update.

Next, we test for the returned value of $this->db->update($data);, which will return true if successful and false if there was an error. If the returned value is true, we grab the number of affected rows for the update with the following line:

return $this->db->affected_rows();  

If the update doesn't happen, the returned value will be false.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.217.134