<p><span style="background-color: initial;">สอบถามเกี่ยวกับ Yii2 CSV Importer to Database ตัวอย่างไหมครับ</span></p>
//upload controllers
public function actionUpload() {
$model = new CsvForm();
if ($model->load(Yii::$app->request->post())) {
$file = UploadedFile::getInstance($model, 'file');
$filename = 'Data.' . $file->extension;
$upload = $file->saveAs('uploads/' . $filename);
if ($upload) {
define('CSV_PATH', 'uploads/');
$csv_file = CSV_PATH . $filename;
$filecsv = file($csv_file);
print_r($filecsv);
foreach ($filecsv as $data) {
$modelnew = new Tblimport;
$hasil = explode(",", $data);
$nim = $hasil[0];
$nama = $hasil[1];
$jurusan = $hasil[2];
$angkatan = $hasil[3];
$alamat = $hasil[4];
$foto = $hasil[5];
$month = $hasil[6];
$year = $hasil[7];
$modelnew->nim = $nim;
$modelnew->nama = $nama;
$modelnew->jurusan = $jurusan;
$modelnew->angkatan = $angkatan;
$modelnew->alamat = $alamat;
$modelnew->foto = $foto;
$modelnew->month = $month;
$modelnew->year = $year;
$modelnew->save();
}
unlink('uploads/' . $filename);
return $this->redirect(['index']);
}
} else {
return $this->render('upload', ['model' => $model]);
}
}
///============= view
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype'=>'multipart/form-data']]); ?>
<div>
<?= $form->field($model,'month')->textInput() ?>
</div>
<div>
<?= $form->field($model,'year')->textInput() ?>
</div>
<div>
<?= $form->field($model,'file')->fileInput() ?>
</div>
<div>
<?= Html::submitButton('อัฟโลหดไฟล์ CSV...',['class'=>'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
ประมาณนี้ครับ
ตอบ/อธิบาย