2011-10-25 30 views
3

我有一些麻煩搞清楚如何讀取我上傳的CSV文件,可能我在我的控制器代碼中缺少一些東西。Yii - 如何上傳一個CSV保存在數據庫中?

public function actionImport() { 
    $model = new Produtos; 
    $this->render('import', array('model' => $model)); 

    if(isset($_FILES['csv_file'])) { 

     $handle = fopen($_FILES['csv_file']['tmp_name'], 'r'); 

     if ($handle) { 
     while(($line = fgetcsv($handle, 1000, ";")) != FALSE) { 
      $model->codigo   = $line[0]; 
      $model->nome   = $line[1]; 
      $model->descricao  = $line[2]; 
      $model->stock   = $line[3]; 
      $model->data_reposicao = $line[4]; 

      $model->save(); 
     }   
     } 
     fclose($handle); 
    } 

    } 

這既節約了我的CSV最後一行...請一些幫助!

任何幫助將非常感激。

謝謝

+0

化妝的var_dump($ _ FILES),你會發現你傳遞一個數組。你需要傳遞一個字符串 – RusAlex

+0

$ _FILES ['csv_file'] [0]?還請確保您的表格中有enctype =「multipart/form-data」 –

+0

@RusAlex謝謝。 – Davidslv

回答

1

不要忘記檢查您的數據是否成功驗證。

插入你之間的這種代碼:

 $model->data_reposicao = $line[4]; 

     if (!$model->validate()) 
      throw new Exception("Validation failed."); 

     $model->save(); 

所以你可以看到什麼錯。

1

$ _FILES是一個包含['element_name'] - 數組的數組。在你的情況下$ _FILES是$ _FILES ['csv_file'] ['name'],$ _FILES ['csv_file'] ['type'],$ _FILES ['csv_file'] ['error'],$ _FILES ['csv_file'] ['size']和$ _FILES ['csv_file'] ['tmp_name']。

所以簡而言之; $ _FILES ['csv_file']是一個數組。

+0

謝謝,但現在我有另一個問題,它只是保存在CSV中的最後一行 – Davidslv

1

您一次又一次地保存相同的模型實例......這就是爲什麼只有最後一行得到保存......您將不得不爲每一行創建一個新模型,即在您的while循環中,添加$model = new Produtos;

0

我知道這是舊的文章,但我只是碰到這種前來,只是想幫助誰可能有同樣的問題(b/W的問題不是採用CSV或文件上傳)

問題是與某人Yii如何處理保存

您需要將isNewRecord屬性設置爲true,並在savin之前將模型對象的主鍵設置爲NULL g每次保存一條新記錄。

$model->PRIMARYKEYCOLUMN = NULL; //Replace PRIMARYKEYCOLUMN with the name of column 
$model->isNewRecord = true; 
$model->save(); 

無論何時在循環中保存行時,都需要執行上述步驟。

1

您需要在每次需要將行插入表格時初始化模型對象。該代碼應該是這樣的:

public function actionImport() { 
    $model = new Produtos; 
    $this->render('import', array('model' => $model)); 

    if(isset($_FILES['csv_file'])) { 

     $handle = fopen($_FILES['csv_file']['tmp_name'], 'r'); 

     if ($handle) { 
     while(($line = fgetcsv($handle, 1000, ";")) != FALSE) { 
      $modeln = new Produtos; 
      $modeln->codigo   = $line[0]; 
      $modeln->nome   = $line[1]; 
      $modeln->descricao  = $line[2]; 
      $modeln->stock   = $line[3]; 
      $modeln->data_reposicao = $line[4]; 

      $modeln->save(); 
     }   
     } 
     fclose($handle); 
    } 

    } 
-1
$handle = fopen($_FILES['Userimportcsv']['tmp_name']['csv_file'], 'r'); 
if($handle) {       
    $row = 1; 
    while(($line = fgetcsv($handle, 1000, ",")) != FALSE) { 
     if($row>1) {  
      $newModel = new Countries; 
      $newModel->countryName  = $line[0]; 
      $newModel->status   = $line[1]; 
      $newModel->save(); 
     } 
     $row++;      
    }      
} 
fclose($handle); 
相關問題