This article will show you how to insert data into database in CodeIgniter. Inserting data into database includes the following steps.

Before continuing, make sure that you have configured the database connection.

You can download the Source code from below link and run on your Local server.

Files to refer:

  • cisite\application\views\examples\insert.php
  • cisite\application\controllers\Example.php
  • cisite\application\models\ExInsert.php
  • cisite\application\config\routes.php

1)  Create the following table ex_insert in your database:

idnameemailgender
int
Auto Increment
varchar(50)varchar(50)varchar(50)
CREATE TABLE cisite.ex_insert 
(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL ,
email VARCHAR(50) NOT NULL ,
gender VARCHAR(50) NOT NULL
);

2) Create view: insert.php and paste the following code.

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>CI data insert example</title>
</head>
<body>
<form action="insertdata" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="save" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>

3) Create a controller: Examples.php and paste the following code.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Examples extends CI_Controller{

public function index($page="insert")
{
switch ($page)
{
case 'insertdata':
$this->InsertData();
return;

case 'insert':
$this->load->view('insert');
break;
default:
echo "Please choose a page"
break;
}
}
public function InsertData()
{
$this->load->model('ExInsert');
$data['name']=$this->input->post('name');
$data['email']=$this->input->post('email');
$data['gender']=$this->input->post('gender');

echo $this->ExInsert->InsertData($data);
}
}
?>

4) Create model: ExInsert.php and paste the following code.

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

class ExInsert extends CI_Model{

public function __construct()
{
parent::__construct();
$this->load->database();
}

public function InsertData($val)
{
$data['name'] = $val['name'];
$data['email'] = $val['email'];
$data['gender'] = $val['gender'];
$this->db->insert('ex_insert', $data);
return 'Data saved';
}
}

5) Create routing:

//Examples start
$route['examples'] = 'Examples';
$route['examples/(:any)'] = 'Examples/index/$1';
//Examples End