Reputation: 6679
I am trying to store multiple records in my database but I'm getting errors. At the moment I have this:
$array=array('key'=>'value');
for($i = 0; $i < $something; $i++){
array_add($array,'key','value')
}
DB::table('table')->insert($array);
Whenever I var_dump($array);
It wont show the values of the array_add
I add into the array.
What am I doing wrong and how should I insert like this?
Upvotes: 1
Views: 1905
Reputation: 152880
What you are currently doing inside the for
loop is setting key => value
again and again. Instead you want to add an array with key => value
to an array containing all the rows:
$rows = array(
array('key' => 'value'),
array('key' => 'value2'),
// and so on...
);
for($i = 0; $i < $something; $i++){
$rows[] = array('key' => 'value');
}
DB::table('table')->insert($rows);
Upvotes: 1
Reputation: 4513
More a comment than an answer... Completely untested code...
Given my interpretation of the question - I think the code should look something like this....
If you wanted to add more than one record then an extra loop enclosing the 'newRecord' would be required.
Feel free to post comments if i misunderstood the question.
$allRecordsToInsert = array();
$newRecord = array();
for($i = 0; $i < $something; $i++) { // add columns to 'newRecord'
array_add($newRecord, $curColKey, $curColValue);
}
// append new record to list of records to be inserted
$allRecordsToInsert[] = $newRecord;
DB::table('table')->insert($allRecordsToInsert);
Upvotes: 0
Reputation: 1165
Here is an answer to this question. Hope this help. https://laracasts.com/discuss/channels/general-discussion/update-multiple-rows-in-a-foreach-loop?page=1#reply-27859
Upvotes: 0