Press "Enter" to skip to content

Updating Database Values in CodeIgniter

Update Data Using CodeIgniter Model Class

If you are familiar with database delete operation, then updating a database data is simple. As we shown in deletion, you can perform update operation using traditional and CodeIgniter specialized quires.

First of all, your Controller class should call a model function for update a data. You may send updating id, values, etc from controller to model that we leant early.

Controller:

  public function update()
   {
     $this->load->Model('ProjectModel');
     $this->ProjectModel->update_data();
     echo "Updated";
   }

Where

  • ProjectModel is the name of CodeIgniter model.
  • update_data is the function name on the model.

Model Class:

As we shown above, we can write model codes in different ways.

  public function update_data()
  {
    $this->load->database();
    $this->db->query("UPDATE table_user SET user_name = 'APK' WHERE user_age =25");
  }

In this traditional way of update query, where table_user is the database table name, user_name and user_age are two column on the table table_user.
Above query updates a user name as ‘APK’ of an age 25.

CodeIgniter Method of Update.

This type of updating is more structure.
  public function update_data()
  {
    $this->load->database();
    $this->db->where('user_age', 25);
    $this->db->update('table_user', array('user_name' => 'Aslam Kakkove'));
  }
  • Here, ‘WHERE’ clause contains a condition for update operation.
  • In update operation, there is an array which contains new values for database updating.

You can add more values and conditions here.

  public function update_data()
  {
    $this->load->database();
    $this->db->where('user_age', 25);
    $this->db->where('user_id', 13);
    $this->db->update('table_user', array('user_name' => 'Aslam PK', 'user_age' => '26'));
  }

Here we don’t pass any value from Controller to Model for updating a data.
As we learnt in previous lesson, there are many ways to send a value from Controller to Model.

Here let us try method of parameter.

Controller:

public function update()
   {
     $age = 25;
     $this->load->Model('ProjectModel');
     $this->ProjectModel->update_data($age);
     echo "Updated";
   }

Here controller pass a variable ‘age’ with value ‘25’ to model class as a function parameter.

Model:

public function update_data($age)
  {
    $this->load->database();
    $this->db->where('user_age', $age);
    $this->db->update('table_user', array('user_name' => 'Aslam'));
  }

 

Model class function accepts the parameter as a variable ‘age’ and in WHERE clause, the variable is used as a condition.

Be First to Comment

Leave a Reply