In this tutorial, we are going to learn CodeIgniter database insertion. After this, you will be able to insert the record in the database within CodeIgniter. We will use two different methodologies of CodeIgniter database pattern to insert the record, for depth knowledge of database pattern you can read the previous tutorial.

You can insert record within database instance which you have manually created by SQL Query which is as follow.

$this->db->query("INSERT INTO users (Name, Age) Values ('Tutorial Pace', 23)");

In the above line of code, we are inserting the record within the user table. The query method is the effective for custom SQL queries. We can do the same process with the help of active record. You can observe active record code as following.

$this->db->insert('user', array('Name' => 'Tutorial Pace','Age' => 23));

Now you can observe by your own the difference between query method and active record query. If you have to perform simple operations you can use active record methods.

The insert method provided as a feature by which we just place the name of the table and pass the array with parameters which we want to insert within the table.

This method will return a bool value. If the record is successfully inserted within a database it will return true or else false. You can store its returned value within any variable to reuse that for other purposes. For an example, we are Wanted to return a custom value whenever a record is inserted. We will do the code as follows.

$Response = $this->db->insert('user', array('Name' => 'Tutorial Pace','Age' => 23));

  $Response = "Data Inserted";
  $Response = "Data Insertion is failed";

echo $Response;

Now in the above code, you can observe we are storing the returned value within “$Response” variable. If the variable contains True Value it will store a “Data Inserted” response within it and if it contains false value it will store “Data Insertion is failed” message which we are printing with the help of “echo”.