In this example, you will learn how to insert CodeIgniter data into an example database. We will show insert data sent by the user in the database table. In this example, I explain the insert record from the CodeIgniter database.


We will show step-by-step inserting data into the database with CodeIgniter. We will show How to insert data into the database with CodeIgniter.


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 & it helps you ...