CodeIgniter Insert Query

In this tutorial you will learn about the CodeIgniter Insert Query and its application with practical example.

In CodeIgniter, insert() method is used to insert record in database table. In order to generate insert statement, insert() method can be used in following ways –

Syntax:-

Here,

$table(String):- Table Name

$set(array):- An associative array of column/value.

$escape(bool):- Whether to escape values and identifiers (TRUE/FALSE)

Returns(bool):- It returns TRUE on success and FALSE on failure.

Example:- Let’s say you have a MySQL table named ’employee_master’ with the following fields –
emp_name, emp_email, emp_phone, emp_address, emp_code and emp_dept

Inserting Data using $this->db->insert()

This is how you can insert a record into ’employee_master’ table using $this->db->insert().

Inserting Data using $this->db->query()

This is how you can insert a record into ’employee_master’ table using $this->db->query().

Inserting Data with Query Bindings

This is how you can insert a record into ’employee_master’ table with Query Binding.

Inserting Data using $this->db->set()

This is how you can insert a record into ’employee_master’ table using $this->db->set().

Inserting Data using $this->db->insert_batch()

The $this->db->insert_batch() method is used to insert batch of records in single query, this is how you can insert batch of record into ’employee_master’ table using $this->db->insert_batch().

Escaping Insert Queries

In CodeIgniter, values can be escaped using $this->db->escape_str() function to produce safer queries.

Retrieve Last Inserted ID

The insert_id() method is used to retrieve the last Inserted ID when performing database inserts.

Retrieve Affected Rows

The affected_rows() method is used to displays the number of affected rows, when doing “write” type queries (insert, update, etc.).

 

In this tutorial we have learn about the CodeIgniter Insert Query and its application with practical example. I hope you will like this tutorial.