I have problem with my code when i'm trying to save multiple data into database at the same time, this is my code to save into database:
foreach ($data as $value) {
$model->route = $value[0][1];
$model->begin_point = $value[0][2];
$model->begin_point = $value[0][3];
$model->save();
}
return $this->redirect('index');
every i'm trying to save, i'm only get the last data array can save into database. could someone help me? or if someone could provide a tutorial, that would be a real help.
Create an array by looping your multiple values.
$data- has multiple values
$bulkInsertArray = array();
foreach($data as $value){
$bulkInsertArray[]=[
'columnName1'=>$value[0][1],
'columnName2'=>$value[0][2],
'columnName3'=>$value[0][3]
];
}
Check $bulkInsertArray in not empty
if(count($bulkInsertArray)>0){
$columnNameArray=['columnName1','columnName2','columnName3'];
// below line insert all your record and return number of rows inserted
$insertCount = Yii::$app->db->createCommand()
->batchInsert(
$tableName, $columnNameArray, $bulkInsertArray
)
->execute();
}
Hope these code may be helpful.
You have to create a New object of the model each time. Or Else youre Just overwriting.
$command = Yii::app()->db->createCommand();
$command->insert('table_name',array('column_1'=>$value_1),
'column_2'=>$value_2));
and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With