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:

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.

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

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

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

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

Pin It on Pinterest

Share This