×

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

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.

CodeIgniter File Helper

The file helper function is used to perform various tasks with files such as accessing files, writing data to files, deleting files, and more. Loading the File Helper Before using the file helper, you must...

7 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.

CodeIgniter Helpers

The Helpers (functions) are stored in the Helper file. It helps CodeIgniter to perform different tasks. The helper file is the collection of many functions that is used to perform specific task. It...

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 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 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.

CodeIgniter CAPTCHA Helper

A CAPTCHA (Complete Automated Public Turning test to tell Computer and Humans Apart) helper is a function that is used in web application to check whether the user is human or machine. It...

3 minutes read.

CodeIgniter Benchmarking Class

The CodeIgniter contains the Benchmarking class that is used to calculate the time difference between two points or the memory usage of the passed statements in the application. By default, the Benchmarking...

7 minutes read.

CodeIgniter URL Helper

The helper file contains some predefined functions that are used to work with URL, such as generate the current file path, transfer control, redirect, create a link, etc. Load the URL Helper Before using...

7 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 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 Tutorial

What is CodeIgniter? CodeIgniter is an open-source framework for developing a dynamic web application with the use of PHP. It uses the MVC framework to develop the project, which is much...

3 minutes read.

CodeIgniter Security Class

Security Class The security class provides various function that helps to create a secure application and process input data securely to the application. This class is preloaded in the CodeIgniter application, so you...

4 minutes read.

Codeigniter Session Library

Session Library The session is an essential part of any application. It contains various functions to manage the users' status and track their activity while browsing on the site. For example,...

13 minutes read.

CodeIgniter Encrypt Class

The Codeigniter provides an encrypt class used to protect confidential data stored on computer systems or data transmitted over a network. It provides two-way data encryption techniques such as Mcrypt PHP extension and...

4 minutes read.

CodeIgniter Text Helper

The text helper contains the various function that is used to operate with text such as define a word limit and characters limit, conversion of word from ASCII to entities, etc. Loading the text...

4 minutes read.

CodeIgniter Shopping Cart Class

It contains the various function that enables the user to add or update, display, and delete data item from the shopping carts while browsing the site. The items added in the cart...

10 minutes read.

CodeIgniter Form Helper

A form helper file contains different functions that works with forms. It is used to create various functionality in a form such as dropdown, radio button, password, upload, hidden data, etc. These functionalities...

12 minutes read.

CodeIgniter Language Class

Language Class The CodeIgniter’s language class contains the various functionality that is used to access the language-specific files and text line for the purposes of internationalization. This class provides you suitability to add or...

4 minutes read.