CodeIgniter Insert Data into Database Example

In this example, You learn CodeIgniter insert data into database example. we will show insert user submitted data into the database table. In this example i explain CodeIgniter Database Insert Record.

We will show step by step insert data into database with codeigniter. we will show How to insert data into database with CodeIgniter.

CodeIgniter Insert Data into Database

Step 1 : Create Controller

In this step we will create Demo.php controller for insert data into database.

<?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 save_demo(){
        $post_data['name'] = "Test";
        $post_data['email'] = "test@gmail.com";
        $post_data['created_at'] = $this->now_time;
        $post_data['updated_at'] = $this->now_time;

        $result = $this->demo_model->insert('demo',$post_data);

        if($result){
            echo "Data Inserted";
        }else{
            echo "Data Not Inserted";
        }
    }
    
    
}


Step 2 : Create Model

Create Demo_model.php model for insert data in codeigniter.

<?php

class Demo_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    /**
     * @param $table_name
     * @param $data_array
     * @return bool
     */
    function insert($table_name,$data_array){
        if($this->db->insert($table_name,$data_array))
        {
            return $this->db->insert_id();
        }
        return false;
    }

}

I hope you understand of insert data in codeigniter and it can hrlp you…