0

I have an array ['abc','xyz'];

I want to insert two rows but in one go

I dont want

loop(){
 $this->db->insert()
 }

this will run insery query two times

Using CI Framework and this array comes from user

PJProudhon
  • 835
  • 15
  • 17
Neeraj Walia
  • 208
  • 3
  • 16

4 Answers4

1
foreach ($this->input->post("name") as $value) {        
            $name[] = array(
                'name'=>$value,
            );
        }
$this->db->insert_batch("names",$name);
Neeraj Walia
  • 208
  • 3
  • 16
0

yourModel.php

public function urfunctionName($data)
{
  foreach($data as $res)
  {
     $this->db->insert('table_name',$res);
  }
}

Hope it will work you

Ramesh S
  • 841
  • 3
  • 15
  • 35
0

You'll need to build your 'batch' insert query first. After that call the insert_batch method.

$array = ['abc','xyz'];
$batchInsertArray = buildBatchInsertArray($array);

$this->db->insert_batch('myTable', $batchInsertArray);

function buildBatchInsertArray(array $array): array
{
    $batchInsertArray = [];

     foreach ($array as $item) {
       $batchInsertArray[] = [
           'columnName' => $item
       ];
    }

    return $batchInsertArray;
}
Daan
  • 12,099
  • 6
  • 34
  • 51
0
$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')

Referance :: query_builder inserting-data

JenuJ
  • 446
  • 5
  • 10