上传CSV文件并使用Laravel将其导入数据库

the*_*_II 4 php pdo laravel-4

我有这种方法上传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

     }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是在这个方法中我怎么能把它放到数据库中?

Gad*_*oma 7

这个应该适合你,它使用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);

}
Run Code Online (Sandbox Code Playgroud)

因此,结合您的代码,它可能类似于下面的内容

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' );            

     }
}
Run Code Online (Sandbox Code Playgroud)

编辑

有一点需要注意,根据您在评论中报告的错误,这可能是一些权限问题(操作系统错误代码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/import".


小智 6

虽然加载数据infile是最快的方式,但我更喜欢使用像https://github.com/ddeboer/data-importhttps://github.com/goodby/csv这样的lib ,原因有两个.

  1. 它是可扩展的,如果您的数据源更改为excel文件或mongo db或其他方法,该怎么办?

  2. 如果您需要转换日期,字符串或数字,您可以有条件地执行它,这是批处理命令无法完成的.

我的2c