Codeigniter Single & Multiple Insert Query

In this Codeigniter Insert Query Tutorial – We would love to share with you how to insert single or multiple records into database. And how we can get last insert id of last inserted record into database.

Here You will learn this insert query with example. We will explain about codeigniter insert record queries with get last insert id.

Codeigniter Insert Query

Content

  • Insert Query
  • Single Record Insert
  • Insert Multiple Record
  • Insert String Query
  • Get Inserted ID
  • Affected Row
$query = "insert into users (name, contact_no, email)
        values ('tutsmake, 8888888888, '[email protected]')";
$this->db->query($query);

Single Record Insert

Syntax :

$this->db->insert('Table_name', $data);

You can use the below query for insert single record into database.

$data = array( 
        'name'  =>  'tutsmake', 
        'contact_no'=> '8888899999', 
        'email'   =>  '[email protected]'
    );
$this->db->insert('users', $data);

Insert Multiple Record

Syntax :

$this->db->insert_batch('table_name', $array_of_data);

You can use the below query for insert multiple recode into database. You can use insert_batch method for inserting or storing multiple record in single query.

$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

Syntax

$this->db->insert_string('table_name', $data);

This function simplifies the process of writing database inserts. This gives the correctly formatted SQL inserted string.

$data = array( 
        'name'  =>  'tutsmake', 
        'contact_no'=> '8888899999', 
        'email'   =>  '[email protected]'
    );
$this->db->insert_string('users', $data);

Get Inserted ID

Syntax

$this->db->insert_id()

After successfully insert a record into database. Last inserted record from database, You can get this last insert id using the insert_id() function of codeigniter.

$data = array( 
        'name'  =>  'tutsmake', 
        'contact_no'=> '8888899999', 
        'email'   =>  '[email protected]'
    );
$this->db->insert('users', $data);
return $this->db->insert_id();

Affected Row

Displays the number of affected rows, when doing “write” type queries (insert, update, etc.).

$this->db->affected_rows();

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *