CodeIgniter: INSERT multiple records without cycle
Asked Answered
D

2

33

It's possible to use multiple INSERT records in CodeIgniter Active Record without for, foreach and etc. ?

My current code:

foreach($tags as $tag) {
    $tag = trim($tag);
    $data = array(
        'topic_id'  =>  $topic_id,
        'user_id'   =>  $user_id,
        'text'      =>  $tag
    );
    $this->db->insert('topic_tags', $data);
}
Desist answered 18/2, 2013 at 22:52 Comment(0)
M
82

Codeigniter active record has a function insert_batch i think that is what you need

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

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')

Works for both Codeigniter 3.x and Codeigniter 2.2.6

UPDATED LINKS

insert_batch() for Codeigniter 3.x

insert_batch() for Codeigniter 2.x

Malia answered 18/2, 2013 at 23:8 Comment(1)
Does this work for edition as well? If the record exist -> update it. If it doesn't exist -> insert it. Off course I would add the id to the inner arrays.Dafodil
V
2

for CodeIgniter 4x use $builder->insertBatch()

$data = [
    [
            'title' => 'My title',
            'name'  => 'My Name',
            'date'  => 'My date'
    ],
    [
            'title' => 'Another title',
            'name'  => 'Another Name',
            'date'  => 'Another date'
    ]
];

$builder->insertBatch($data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

Source

Valediction answered 14/1, 2021 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.