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 ...

Get CodeIgniter 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.