CodeIgniter Insert Data

In this section, We'll understand how to insert data into database using Controller Model and View. We'll use tbl_users table to insert, display, update and delete data.

create a table named "tbl_users".

CREATE TABLE tbl_users(
        name VARCHAR(32) NOT NULL,
        email VARCHAR(32) NOT NULL,
        contact_no VARCHAR(32) NOT NULL,
        primary key(id)

Using a text editor, create a controller called User.php. In it, place this code and save it to your application/controllers/ directory:

   class User extends CI_Controller {
      public function __construct() { 
         $this->load->helper(array('form', 'url')); 
      public function index() {
         /* Load form validation library */ 
	 /* Validation rule */
	 $this->form_validation->set_rules('name', 'Name', 'required');
	 $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
	 $this->form_validation->set_rules('contact_no', 'Contact Number', 'required');		 
         if ($this->form_validation->run() == FALSE) { 
         else { 
		    $success = "Submit successfully!";
                    $this->load->view('user_form', compact('success')); 

Using a text editor, create a form called user_form.php. In it, place this code and save it to your application/views/ directory:

<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="" />
<script src=""></script>
<script src=""></script>
<div class="container">
  <div class="col-md-2"></div>
     <div class="col-md-8" style="margin-top:20px">
		   echo form_open('user/index');
		   echo validation_errors();
		   if (isset($success))
		   echo '<p>'.$success.'</p>';
		<div class="form-group">
			<label for="email">Name:</label>
			<input type="text" id="name" name="name" />
		<div class="form-group">
			<label for="email">Email:</label>
			<input type="text" id="email" name="email" />
		<div class="form-group">
			<label for="contact_no">Contact Number:</label>
			<input type="text" id="contact_no" name="contact_no" />
		<button type="submit" class="btn btn-success">Submit</button>
		echo form_close(); 
	 <div class="col-md-2"></div>

Using a text editor, create a model called User_model.php. In it, place this code and save it to your application/models/ directory:

class User_model extends CI_Model
    public function save()
	   $data['name'] = $this->input->post('name');
	   $data['email'] = $this->input->post('email');
	   $data['contact_no'] = $this->input->post('contact_no');
	   $this->db->insert('tbl_users', $data);

To try your form, visit your site using a URL similar to this one:


codeigniter insert data into database codeigniter insert data into database2 codeigniter insert data into database3 codeigniter insert data into database4 codeigniter insert data into database5