×

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

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.

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

Directory Helper Codeigniter

Directory Helper CodeIgniter: provides a directory helper function that works with the directory. It shows the structure of the file, hidden file in the folder, and the folder in...

3 minutes read.

CodeIgniter User Agent Class

User Agent Class The CodeIgniter provides a user agent class that helps to identify and collect information about the browser, mobile devices, or robots visiting your site. Besides this, it is also used...

4 minutes read.

CodeIgniter Input Class

Input Class The CodeIgniter framework provides an input class that includes various input functions to pre-process global input data for protection; furthermore, it also provides some helper functions to obtain input data. This...

11 minutes read.

Retrieve data from Database

Retrieve data from the Database Now we will discuss how we can retrieve data from the database that we have inserted to the employees table of the database in our previous topic “inserted...

2 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 ZIP Encoding Class

ZIP Encoding Class The CodeIgniter provides a Zip encoding class that are used to compress a large file into a Zip archives. And this archives files can be downloaded either to your desktop or...

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

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.

Database Configuration CodeIgniter

In every application, there is an important part of a database through which developers can connect an application to store users’ data and perform various functions in the database application such as inserting,...

10 minutes read.

CodeIgniter String Helper

The string helper file contains functions that allows separate operations with strings in CodeIgniter. Loading the String Helper Before using the string helper in the CodeIgniter application, you must load it in the controller...

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

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 Email Class

CodeIgniter provides an e-mail library that helps to send a message from one application to another. You can create and send text messages easily in CodeIgniter application even you can set email...

9 minutes read.

CodeIgniter Date helper

A date helper file contains some predefined functions that work with date functions. Before using the date function in CodeIgniter, you have to load the date helper in the controller. For example: $this->load->helper(‘date’); Functions of...

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

Update a Record CodeIgniter

Update a record In this topic, we will learn how we can update existing records in database tables. To update a record, CodeIgniter provides an update() function used with the set()...

10 minutes read.