Lerry
Lerry

Reputation: 146

Codeigniter array insert into database

I have started using codeigniter before some days and must say it is one of d great framework I have found.

Currently issue I am facing is with multiple insert record.

There are dynamic generated records I require to add in table and I have done with that loop as well like :

for ($i=0;$i<count($arr);$i++)
{
   // Insert query here
}

However, this slow down process and also not efficient way, Is there anythig I can use for smooth insert ?

Upvotes: 0

Views: 763

Answers (3)

Pathik Vejani
Pathik Vejani

Reputation: 4491

Use this:

$data = array(
   array(
      'title' => 'title_one' ,
      'name' => 'name_one' ,
      'dob' => 'birth_date_one'
   ),
   array(
      'title' => 'title_two' ,
      'name' => 'name_two' ,
      'dob' => 'birth_date_two'
   )
);
$this->db->insert_batch('table_name', $data); 

Upvotes: 1

hitamu
hitamu

Reputation: 27

You can use make the query by yourself and call it like that:

$query = $this->db->query($sql);

Example

// Create sql query
$sql = 'insert into `table_name` (
            `field_1`,
            `field_2`, 
            `field_3`, 
            `field_4`,
        ) 
        values ';
// Value of each column
foreach ($arr as $data) {       
    $sql .= "("
         . "'" . $data['field_1_name'] . "',"
         . "'" . $data['field_2_name'] . "',"
         . "'" . $data['field_3_name'] . "',"
         . "'" . $data['field_4_name'] . "',"
    "),";
}
// Query to db
try {
    $sql = rtrim($sql, ',');
    return $this->_model->query($sql);
} catch (Exception $e) {
    return false;
}

Upvotes: 0

CodeWithCoffee
CodeWithCoffee

Reputation: 1904

What you can do is use of Batch functionality provided by codeigniter.

So you can do it like :

$data = array(
   array(
  'title' => 'My title' ,
  'name' => 'My Name' ,
  'date' => 'My date'
 ),
 array(
  'title' => 'Another title' ,
  'name' => 'Another Name' ,
  'date' => 'Another date'
)
);

$this->db->insert_batch('mytable', $data)

For more information on this, pleas refer : https://ellislab.com/codeigniter/user-guide/database/active_record.html (This example i have added from this page itself)

Upvotes: 2

Related Questions