我有这种方法上传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
}
}
所以我的问题是在这个方法中如何将它放入数据库?
答案 0 :(得分: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);
}
结合您的代码,它可能类似于下面的
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代表'其他' 目录:/ tmp / tmp / imports
以及主要的两个:/ tmp / imports / site1 /tmp/imports/site1/data.file
总结一下:
要解决“sqlstate hy000一般错误13无法获取...的统计信息”问题,您必须将上传的文件移动到具有适当权限的位置(因此不必使用当前正在使用的文件)尝试“/ tmp”之类的操作/进口”。
答案 1 :(得分:6)
虽然加载数据infile是最快捷的方式,但我更喜欢使用像https://github.com/ddeboer/data-import或https://github.com/goodby/csv这样的库,原因有两个。
它是可扩展的,如果您的数据源更改为excel文件或mongo db或其他方法,该怎么办?
如果您需要转换日期,字符串或数字,您可以有条件地执行此操作,这是批处理命令无法完成的。
my 2c