簡體   English   中英

上傳CSV文件並使用Laravel將其導入數據庫

[英]Upload CSV file and import it to database using Laravel

我有這種方法上傳CSV格式的文件,但現在我想知道如何將其上傳到我的數據庫中的列。

我的方法:

 public function postUpload ()
{
    if (Input::hasFile('file')){

        $file = Input::file('file');
        $name = time() . '-' . $file->getClientOriginalName();
        // Moves file to folder on server
        $file->move(public_path() . '/uploads/CSV', $name);


        return 'Ok'; // return for testing

     }
}

所以我的問題是在這個方法中我怎么能把它放到數據庫中?

這個應該適合你,它使用PDO + mySql的“LOAD DATA”方法

private function _import_csv($path, $filename)
{

$csv = $path . $filename; 

//ofcourse you have to modify that with proper table and field names
$query = sprintf("LOAD DATA local INFILE '%s' INTO TABLE your_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\\n' IGNORE 0 LINES (`filed_one`, `field_two`, `field_three`)", addslashes($csv));

return DB::connection()->getpdo()->exec($query);

}

因此,結合您的代碼,它可能類似於下面的內容

public function postUpload ()
{
    if (Input::hasFile('file')){

        $file = Input::file('file');
        $name = time() . '-' . $file->getClientOriginalName();

        //check out the edit content on bottom of my answer for details on $storage
        $storage = '/some/world/readible/dir'; 
        $path = $storage . '/uploads/CSV';

        // Moves file to folder on server
        $file->move($path, $name);

        // Import the moved file to DB and return OK if there were rows affected
        return ( $this->_import_csv($path, $name) ? 'OK' : 'No rows affected' );            

     }
}

編輯

有一點需要注意,根據您在評論中報告的錯誤,這可能是一些權限問題(操作系統錯誤代碼13:權限被拒絕)

請參閱: http//dev.mysql.com/doc/refman/5.1/en/load-data.html

“出於安全原因,在讀取位於服務器上的文本文件時,文件必須駐留在數據庫目錄中或者所有人都可以讀取。另外,要在服務器文件上使用LOAD DATA INFILE,您必須具有FILE權限。請參閱第5.7節.3,“MySQL提供的權限”。“

正如在mySql錯誤跟蹤器( http://bugs.mysql.com/bug.php?id=31670 )上所報告的那樣,您似乎需要csv文件路徑中所有文件夾的特定權限:

infile的所有父目錄都需要世界可讀的我認為以及目錄和infile ...

所以對於這里的infile:/tmp/imports/site1/data.file

你需要(我認為,755工作)r + x這些目錄上的'other':/ tmp / tmp / imports

以及主要的兩個:/ tmp / imports / site1 /tmp/imports/site1/data.file

總結一下:
要解決“sqlstate hy000一般錯誤13無法獲取...的統計信息”問題,您必須將上傳的文件移動到具有適當權限的位置(因此不必使用當前正在使用的文件)嘗試“/ tmp”之類的操作/進口”。

雖然加載數據infile是最快的方式,但我更喜歡使用像https://github.com/ddeboer/data-importhttps://github.com/goodby/csv這樣的lib,原因有兩個。

  1. 它是可擴展的,如果您的數據源更改為excel文件或mongo db或其他方法,該怎么辦?

  2. 如果您需要轉換日期,字符串或數字,您可以有條件地執行它,這是批處理命令無法完成的。

我的2c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM