2015-10-22 117 views
4

我对web开发非常陌生。无法将数据csv导入到yii2的数据库中

我在这里新手,我在计算器的第一个问题..

我感到困惑的代码是什么错误,代码将数据存储阵列的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' 
     ]; 
    } 
} 

感谢帮助..

+2

你收到什么错误?发布您的错误或附加错误截图可能会有所帮助 –

+1

PHP具有本机功能,可以使用CSV。 http://php.net/manual/en/function.fgetcsv.php – SiZE

回答

0

终于它与改变这$hasil = explode(";", $data);

0

改变你的代码如下输出错误,当您尝试可能发生保存。根据您的模型规则可能会出现错误。

if (!$modelnew->save()) { 
    var_dump($modelnew->getErrors()); 
} 

getErrors() from Api

一个更好的办法是使用异常抛出,赶上你的导入错误。取决于您是否想要跳过错误的csv行。