我对网络开发很陌生。
我是新手,这是我在stackoverflow中的第一个问题..
我很困惑代码上的错误,Code会将数据存储数据csv存储到数据库中, 抱歉,我的英语不好。
控制器
public function actionUpload()
{
$model = new Skt();
//error_reporting(E_ALL);
//ini_set('display_error', 1);
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);
foreach ($filecsv as $data) {
$modelnew = new Skt();
$hasil = explode(",", $data);
$no_surat= $hasil[0];
$posisi= $hasil[1];
$nama= $hasil[2];
$tgl_permanen= $hasil[3];
$grade= $hasil[4];
$tgl_surat= $hasil[5];
$from_date = $hasil[6];
$to_date = $hasil[7];
$modelnew->no_surat = $no_surat;
$modelnew->posisi = $posisi;
$modelnew->nama = $nama;
$modelnew->tgl_permanen = $tgl_permanen;
$modelnew->grade = $grade;
$modelnew->tgl_surat = $tgl_surat;
$modelnew->from_date = $from_date;
$modelnew->to_date = $to_date;
$modelnew->save();
//print_r($modelnew->validate());exit;
}
unlink('uploads/'.$filename);
return $this->redirect(['site/index']);
}
}else{
return $this->render('upload',['model'=>$model]);
}
return $this->redirect(['upload']);
}
模型
class Skt extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'skt';
}
public $file;
public function rules()
{
return [
[['file'], 'required'],
[['file'], 'file', 'extensions' => 'csv', 'maxSize' => 1024*1024*5],
[['no_surat'], 'required'],
[['tgl_surat', 'from_date', 'to_date'], 'string'],
[['no_surat', 'posisi', 'nama', 'tgl_permanen', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'no_surat' => 'No Surat',
'posisi' => 'Posisi',
'nama' => 'Nama',
'tgl_permanen' => 'Tgl Permanen',
'grade' => 'Grade',
'tgl_surat' => 'Tgl Surat',
'from_date' => 'From Date',
'to_date' => 'To Date',
'file' => 'Select File'
];
}
}
感谢帮助..
答案 0 :(得分:0)
将代码更改为以下内容,以输出尝试保存时可能发生的错误。根据您的模型规则,可能会出现错误。
if (!$modelnew->save()) {
var_dump($modelnew->getErrors());
}
更好的方法是使用异常来导入和捕获导入错误。取决于你是否想要跳过错误的csv行。
答案 1 :(得分:0)
最后它正在改变这个$hasil = explode(";", $data);