0

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 ?

1
  • i think you should use insert_batch.. Commented May 22, 2015 at 9:06

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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); 

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.