In this tutorial, we would love to share with you how to insert records into database using insert query in codeIgniter projects.
How Insert Data into Database in CodeIgniter
Here are some methods that help to implement query for insert data into a database:
- Query Function with Insert Data
- Single Record Insert using insert()
- Multiple Records Insert using Batch Insert
- Insert String Query
- Get Inserted ID
Query Function with Insert Data
The query function allow users to execute SQL query into it to insert data into a database:
$query = "insert into users (name, contact_no, email)
values ('tutsmake, 8888888888, '[email protected]')";
$this->db->query($query);
Single Record Insert using insert()
$this->db->insert(‘Table_name’, $data) function takes two parameters first is the name of the table and second is the data you want to insert into the database table:
$this->db->insert('Table_name', $data);
Here is an example to insert single record into the database using insert query:
$data = array(
'name' => 'tutsmake',
'contact_no'=> '8888899999',
'email' => '[email protected]'
);
$this->db->insert('users', $data);
Multiple Records Insert using Batch Insert
$this->db->insert_batch(‘table_name’, $array_of_data) function takes two parameters first is the name of the table and second is the array of data you want to insert into the database table:
$this->db->insert_batch('table_name', $array_of_data);
Here is an example to insert multiple recode into database using insert_batch method:
$data = array(
array(
'name' => 'tutsmake',
'contact_no'=> '8888899999',
'email' => '[email protected]'
),
array(
'name' => 'tutsmake.com',
'contact_no'=> '8888899999',
'email' => '[email protected]'
),
),
$this->db->insert_batch('users', $data);
Insert String Query
$this->db->insert_string(‘table_name’, $data) function makes it easy to insert data into the database, and it gives correctly formatted SQL insert string data.
$this->db->insert_string('table_name', $data);
Here is an example of insert_string() method:
$data = array(
'name' => 'tutsmake',
'contact_no'=> '8888899999',
'email' => '[email protected]'
);
$this->db->insert_string('users', $data);
Get Inserted ID
The insert_id() function inserts data into the database as well as returns the last inserted ID:
$this->db->insert_id();
Here is an example of insert_id():
$data = array(
'name' => 'tutsmake',
'contact_no'=> '8888899999',
'email' => '[email protected]'
);
$this->db->insert('users', $data);
return $this->db->insert_id();