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

10
  • What DB controller are you using? Commented Oct 30, 2018 at 10:06
  • @WKoppel Using CI Framework Commented Oct 30, 2018 at 10:07
  • inside loop write insert query Commented Oct 30, 2018 at 10:07
  • @Daan This is something manual taking values from input in array what can i do? Commented Oct 30, 2018 at 10:08
  • 1
    Please read the manual before asking, I found this on google within 10 seconds: insert_batch codeigniter.com/userguide3/database/… Commented Oct 30, 2018 at 10:09

4 Answers 4

1
foreach ($this->input->post("name") as $value) {        
            $name[] = array(
                'name'=>$value,
            );
        }
$this->db->insert_batch("names",$name);
Sign up to request clarification or add additional context in comments.

2 Comments

would you like to explain the code so that the OP decides why he needs to update the code to this one
Thanks for your answer. Please provide some description to your code-example.
0

yourModel.php

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

Hope it will work you

3 Comments

I told you not to do this in loop
Show me your expected result
I will get same results but your code will run query equal to length of my array like if array has 100 indexes it will run 100 times which is not good i want to insert 100 rows in one run thanks for help insert_batch() did it thankyou all
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;
}

Comments

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

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.