×

Insert data to the database CodeIgniter

After successfully creating a database connection with the CodeIgniter application, we will now understand how we can insert records into the database.

To insert a record into a database table, Codeigniter provides an insert() method  which is shown in the following syntax:

insert([$table = ‘’[, set = NULL[, $escape = NULL]]])

It has three parameters:

$table: It defines the name of the table.

$set(array): It consists of an associative array of key/value pairs.

$escape(bool): It defines whether to escape a value and an identifier.

The following example shows how we can insert records in the customer table.

$record = array(
             ‘cust_id’ => ‘10’,
             ‘cust_name’ => ‘peter’,
             ‘cust_email’ => ‘cust@xyz.com’
 );
 $this->db->insert(‘customer’, $record); 

A $record is an array in which data is placed in keys/pairs. Now we have to insert that records into a customer table. Therefore, we call an insert function where the first parameter denotes the customer table, and the second one contains the record which is kept in the customer table.

Before inserting a record into the database, you must define a table "employees" and its attributes in the database, as shown in the image below.

Insert data to the database

After creating the table “employees” and its attributes in a “codedb” database, you have to create three files toinsert the values into the table, as shown below:

  1. Employee_controller.php
  2. add_view.php
  3. data_model.php

Create a controller file Employee_controller.php and save it in application/controller/Employee_controller.php. After that, write the following program in the controller file.

Employee_controller.php

<?php
 defined('BASEPATH') OR exit( 'No direct script access allowed');
 class Employee_controller extends CI_Controller 
 {
  function _construct()
     { 
         parent::_construct();
         $this->load->model('data_model');
     } 
    public function insert_data()
    {
        $this->load->database(); 
     $this->load->helper('form'); // load form helper
     $this->load->library('form_validation'); // load form_validation library
     $this->load->model('Data_Model'); // load Data_Model
           // set validation to the name 
     $this->form_validation->set_rules('name', 'Full Name', 'required'); 
      // set validation to an email
     $this->form_validation->set_rules('email', 'Email', 'required');
       // set validation to the name
     $this->form_validation->set_rules('age', 'Age', 'required');
         // set validation to the name 
     $this->form_validation->set_rules('company', 'Company Name', 'required');
       // set validation to the name   
  $this->form_validation->set_rules('mob', 'Mobile No. ', 'required');
    // set validation to the name
     $this->form_validation->set_rules('country', 'Country', 'required'); 
     if ($this->form_validation->run() == FALSE)
     {
             $this->load->view('add');
     }
     else 
     {    
         $records = array(
             'name' => $this->input->post('name'),
             'email' => $this->input->post('email'),
             'age' => $this->input->post('age'),
             'company' => $this->input->post('company'), 
             'mob' => $this->input->post('mob'),
             'country' => $this->input->post('country')
         );
         $this->Data_Model->add_data($records); // send data to the Data_Model file
        $records['message'] = 'Details has been successfully Submitted';
         $this->load->view('add', $records); // load add view file 
     } 
 }
 ?> 

Create a view file add.php and save it in application/views/add.php. After that, write the following program in the view file.

add.php

<!DOCTYPE html>
 <html>
 <head>
 <title>Tutorial and Example </title>
 </head>
 <body> 
 <?php echo form_open('Employee_controller/insert_data'); ?>
              <div align="center"> <h2>Employee Registration Form </h2></div>
                                <fieldset width="80%">
                                <legend>Details </legend>
          <p style="bgcolor:blue">  <?php if (isset($message)) { ?>
 <CENTER> <h3 style="color:green;">Details has been successfully Submitted</h3> </CENTER><br>
 <?php   
 } 
 ?> </p> 
       <table align="center" width="60%" border="0" bordercolor="green"> 
 <tr><td align="left" valign="top" width="50%"> 
       Full Name :<span class="error" style="color:red">* </span></td> 
       <td > <span style="color:red"> <?php echo form_error('name'); ?> </span><input type="text" name="name" value="<?php echo set_value('name'); ?>" style= "width:100%"placeholder="Enter the Name" 
       title="Please, ProvideYour Full Name !">     
 </td> </tr>
 <tr><td align="left" valign="top" width="50%">
       Your Email-ID : <span class="error" style="color:red">* </span>  </td> 
       <td > <span style="color:red"> <?php echo form_error('email'); ?> </span> <input type="email" name="email" size="30" value="<?php echo set_value('email'); ?>" style= "width:100%" placeholder="Enter the email id"
                   title="Please, Provide Your Personal Email-ID!">    
 </td></tr>
 <tr>
 <td align="left" valign="top" width="50%">  
 Employee Age :<span style="color:red">*</span>:</td>
                   <td ><span style="color:red"> <?php echo form_error('age'); ?> </span> <input type="date" value="<?php echo set_value('age'); ?>" 
                   placeholder="Your Age...." name="age" style= "width:100%"; ></td></tr>
 <tr><td align="left" valign="top" width="50%"> 
       Company : <span class="error" style="color:red">* </span> </td>
       <td > <span style= "color:red"> <?php echo form_error('company'); ?> </span> <input type="text" placeholder= "Enter the Oraganisation name" name="company" value="<?php echo set_value('company'); ?>" style= "width:100%" title="Password should be alphanumeric">     
 </td></tr>
 <tr><td align="left" valign="top" width="50%">
       Mobile No. :<span class="error" style="color:red">* </span>  </td> 
       <td > <span style= "color:red"> <?php echo form_error('mob'); ?> </span> <input type= "number" name= "mob" value="<?php echo set_value('mob'); ?>" style= "width:100%" placeholder= "83685********" title="Please, Provide only Your Personal Contact Number !">       
 </td> </tr>
 <tr> <td align="left" valign="top" width="50%">
       Country :<span class= "error" style= "color:red">* </span> </td>
       <td > <span style= "color:red"> <?php echo form_error('country'); ?> </span> <input type="text" name="country" style= "width:100%" value= "<?php echo set_value('country'); ?>"
       placeholder= "Enter the country name" >       
 </td></tr>
 </table>
 <div align="center"><input type="submit" value="Submit" style="color:Blue" />
 <input type="reset" value="RESET" > </div>
 </fieldset>
 <?php echo form_close(); ?>
 </body> 
 </html> 

Create a model file Data_Model.php and save it in application/Model/Data_Model.php. After that, write the following program in the model file.

Data_Model.php

<?php
 class Data_Model extends CI_Model{
 public function __construct() {
 parent::__construct();
 }
 public function add_data($data)
 {
     $this->load->database(); // load database 
 if ($this->db->insert('employees', $data)) // insert $data into the employees table
 {
 return true;
 }
 }
 }
 ?> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/Employee_controller/insert_data function; It shows the output as shown below.

Insert data to the database

Now fill the Employee Registration form and click on the Submit button, as shown in the image below:

Insert data to the database

After clicking the submit button, you will get the following screen as shown in the below image:

Insert data to the database

If you want to add more entries to the registration form, click the “Add Employee” link, and it will reopen this form to add a new entry to the employees table.

And if you want to verify whether your registration details were successfully saved in the employees table, go to phpMyAdmin and click on the table you built in your database, as shown in the image below.

Insert data to the database

Related Topics

Insert data to the database CodeIgniter

After successfully creating a database connection with the CodeIgniter application, we will now understand how we can insert records into the database. To insert a record into a database table, Codeigniter provides...

8 minutes read.

CodeIgniter Calendaring Library

The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar design. Load...

7 minutes read.

CodeIgniter Inflector Helper

The inflector helper file contains some predefined function that allows users to change their English words into plural, singular, and camel case, etc. Loading an Inflector Helper Before using an inflector helper function, you must...

3 minutes read.

HTML Table Class CodeIgniter

HTML Table Class The CodeIgniter framework provides an HTML Table Class that is used to develop an auto-generated table using a defined array or result sets of the database table. Loading an HTML Table Class...

8 minutes read.

CodeIgniter Controller

As its name suggest that it is a Controller that controls the web application, and it works as an intermediary between the Models and the View. A controller takes requests from the user...

3 minutes read.

Installation of CodeIgniter

Before installing CodeIgniter, you need to make sure that the wamp or xampp server in the system is preinstalled. The installation procedure for CodeIgniter is very easy. You can download CodeIgniter by following these...

2 minutes read.

CodeIgniter Security Helper

A Security helper file contains some predefined functions that are used to protect application from unauthorized access. Loading the Helper The following syntax is used to load the security helper in the CodeIgniter application. Syntax $this-> load->...

4 minutes read.

CodeIgniter Creating Library

As we know, CodeIgniter has a large collection of library functions that are stored in the system/libraries folder. CodeIgniter also provides some additional functionality in library files. For example, if you want to...

3 minutes read.

CodeIgniter Models

Models are the classes that deals with backend operations. It is used to fetch the data from the database and send it to the Controller. All the database related information provided inside...

5 minutes read.

CodeIgniter Views

A View is a presentational part which shows the information to the users. It is a complex web page which contains navbar, header, footer, sidebar, etc. A view file cannot be called directly...

5 minutes read.

Delete a record from Database CodeIgniter

Delete a record from the Database After inserting, retrieving, and updating table records, we will now learn how we can delete a particular record from a database table. To delete a record, first, we...

6 minutes read.

CodeIgniter Output class

Output class The CodeIgniter framework contains a core class that is an Output class. It  includes the various functions that are used to send the final web page to the requesting browser. In...

8 minutes read.

CodeIgniter Array Helper

The Array Helper contains some predefined functions that are used to perform the various operation with array. Load Array helper It is used to load the helper class. We can pass the helper function in the...

6 minutes read.

Migration Class CodeIgniter

The CodeIgniter framework provides the migration class that helps the web developers to create and handle databases in a structured and streamlined manner. The migration classes are very useful when more than...

6 minutes read.

Form Validation Library Codeigniter

Form Validation Library The Codeigniter provides a form validation library that contains predefined rules to validate the form fields. It also helps in optimizing the form validation code, which reduces the effort and time...

31 minutes read.

Image Manipulation Codeigniter

Image Manipulation A Codeigniter provides an image manipulation class that is used for resizing, cropping, rotation, and many other manipulation tasks. This class also support three major image libraries such as GD/GD2, NetPBM, and...

11 minutes read.

How to remove an index.php file from the Codeigniter URLs?

As we know, a URL in CodeIgniter is designed in such a way that it would be search engine and human friendly, too, rather than using a standard approach to create a...

2 minutes read.

CodeIgniter Routes

The Routes are used to handle URL requests on the browser. It matches the URL request to the predefined routes in CodeIgniter. Therefore, a file must be predefined as a routes.php file to...

6 minutes read.

Calendaring Class CodeIgniter

Calendaring Class The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar...

6 minutes read.

CodeIgniter Libraries

The library is an important part of the CodeIgniter framework. It has a large collection of libraries files that are used to increase the performance of an application. By default, all CodeIgniter libraries...

4 minutes read.