2015-10-22 177 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行。