Neeraj Walia
Neeraj Walia

Reputation: 228

Php - Insert Multiple Rows in Ci

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

Upvotes: 0

Views: 68

Answers (4)

JenuJ
JenuJ

Reputation: 456

$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

Upvotes: 0

Neeraj Walia
Neeraj Walia

Reputation: 228

foreach ($this->input->post("name") as $value) {        
            $name[] = array(
                'name'=>$value,
            );
        }
$this->db->insert_batch("names",$name);

Upvotes: 1

Daan
Daan

Reputation: 12246

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

Upvotes: 0

Ramesh S
Ramesh S

Reputation: 804

yourModel.php

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

Hope it will work you

Upvotes: 0

Related Questions