In this tutorial, we are going to learn about CodeIgniter database update operation. In the previous tutorial, we have inserted a sample data regarding the user within the manually created database instance. Codeigniter update method will give you easy to update the record efficiently.

In the conventional development, we have to create a connection first to perform any operation on the database. But with CodeIgniter framework we don’t need to create and close database connections for any operation. We can use a query within a query method or we can use active record update method to update any data within the database.

Whenever you will update any record within a database it will return a Boolean either it is true or false. As I have already explained in the previous tutorial with an example of Boolean extracted from the insertion of data.

In the following example we are going to insert record within the database and then we will update that right after insertion.

Method 1:

$this->db->insert('user', array('Name' => 'Tutorial Pace','Age' => 23));

$this->db->where('table_id', $id)->update('user', array('Name' => 'Tutorial Pace','Age' => 23));

Method 2:

$this->db->insert('user', array('Name' => 'Tutorial Pace','Age' => 23));
$this->db->where('table_id', $id);
$this->db->update('user', array('Name' => 'Tutorial Pace','Age' => 23));

Method 3:

$this->db->insert('user', array('Name' => 'Tutorial Pace','Age' => 23));

$data = array(
               'Name' => 'Tutorial Pace',
               'Age' => 23
            );

$this->db->where('table_id', $id);
$this->db->update('user', $data);

All of these methods are similar and work alike. But the difference is within the logic. Mostly these three methodologies are used. Even that you can create your own logic to update the record.

  • In the first method, we are using the most shortcode to update the record.
  • In the second method, we have separated the where clause with the update clause but the result will be the same.
  • In the third method, we are creating an array of changes which we want to perform within the database. Then pass that array within the update method as a parameter.

The third methodology is used when we have huge data then we will create a sample model to bind that with the database. As you have observed all the attribute are attached in an array and that pass to update method.