CodeIgniter Update Data in Database

In this example, We will learn codeigniter update data in database, codeigniter update database record, codeigniter update database, update data in codeigniter example.

In this post, We will explain step by step codeigniter update data array using codeigniter update function. Also i explain codeigniter update record and update data by id in codeigniter.

Read also : CodeIgniter Insert Data into Database Example

CodeIgniter update data in database example

Step 1 : Create controller

Create a new application/controllers/Demo.php file and following the code.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Demo extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('demo_model');
        $this->now_time = date('Y-m-d H:i:s');
    }
    
    function update_demo(){
        $post_data['name'] = "Demo";
        $post_data['email'] = "demo@gmail.com";
        $post_data['updated_at'] = $this->now_time;

        $result = $this->demo_model->update('demo',$post_data, array("id" => 1));
        if($result){
            echo "Demo updated";
        }else{
            echo "Demo not updated";
        }
    }   
}

Step 2 : Create Model

Create a new application/models/Demo_model.php file and following the code. $this->db->update() function to update data in codeigniter.

<?php

class Demo_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    /**
     * @param $table_name
     * @param $data_array
     * @param $where_array
     * @return mixed
     */
    function update($table_name,$data_array,$where_array){
        $this->db->where($where_array);
        $rs = $this->db->update($table_name, $data_array);
        return $rs;
    }
}

I hope you understand of codeigniter update data and it can help you..

Read also : Get all Data from Database in CodeIgniter