How to insert record in the table using php codeigniter

I last section we saw how to setup codeignitor project. Now we are concentrate on Database side. Let start with insert record example using codeignitor DB classes.

As you know that Php Codeigniter is lightweight mvc framework for PHP. It provides you facility to divide your application into different layers say controller , model and view. Lets drill down the details

Create table "trn_employee"

Use below mysql script to create table in database

CREATE TABLE  `trn_employee` (
  `emp_id` int(10) unsigned NOT NULL auto_increment,
  `emp_name` varchar(45) collate latin1_general_ci NOT NULL,
  `emp_salary` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`emp_id`)
);

Model Class(EmployeeModel.php)

Create a model class which is used to insert the employee record into the database table.

<?php
class EmployeeModel extends Model {

 function EmployeeModel(){
  parent::Model();  
 }
  
 function insertEmployee($employee){ 
  $this->db->insert('trn_employee', $employee); // insert data into `trn_employee` 
  //table 
 }
}
?>

Create Controller Class(Employee.php)

This controller class accepts the input paramters from view page and convert that parameters into $employee object, and with the help of employee model object we are going to insert data into trn_employee table. You need to load model class object in controller class $this->load->model('EmployeeModel');

<?php
class Employee extends Controller {

 function Employee(){
  parent::Controller();
  // load the employee model
  $this->load->model('EmployeeModel');
 }

 function index(){
  // create data
  $employee = array(
    'EMP_ID' => 1,
    'EMP_NAME' =>"Sunil",
    'EMP_SALARY' =>18000    
  );
  // table column name should be same as data object key name
  $this->EmployeeModel->insertEmployee($employee); // call the employee model
  $data['EMPLOYEE_DETAILS'] = $employee;
  $this->load->view('employeeresult', $data);
 }

}
?>