简体   繁体   English

上传csv并将其导入mysql数据库

[英]Upload a csv and import it into the mysql database

I am writing the following script up import a csv file into a mysql database. 我正在编写以下脚本将csv文件导入mysql数据库。 The user has to log in first and their security rights to upload are checked by another file, if this evaluates to true, the file can then be uploaded by the file up-loader which will only allow csv's to be uploaded and then the following part imports the file. 用户必须先登录,并且他们的上传安全权限由另一个文件检查,如果评估结果为true,则文件可以通过文件up-loader上传,只允许csv上传,然后是以下部分导入文件。

Am I using the correct code for this below ?, also if the csv layout is wrong is it possible to refuse the import ?, im just concerned that this could go badly wrong if the csv is formatted correctly. 我是否在下面使用了正确的代码?,如果csv布局错误,是否可以拒绝导入?我只是担心如果csv格式正确,这可能会出错。 This feature has been requested as a requirement for this project so I am just trying to make it as idiot proof as possible for them. 此功能已被要求作为此项目的要求,所以我只是想尽可能地为它们做出白痴证明。

<?php
$uploadedcsv = './uploads/'.$filename.'';
$sql = 'LOAD DATA LOCAL INFILE "'.$uploadedcsv.'" INTO TABLE '.$table.' FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY """" IGNORE 1 LINES' or die(mysql_error());
?>

Unless you are 100% rely on the user and it seems that you are not, it will be good not to blindly import uploaded file, but first to check if it's correct. 除非你100%依赖用户而且似乎你不是,所以不要盲目导入上传的文件,但首先要检查它是否正确。

To do it, you'll need to open and to read the file, eg with fgetcsv and to check the data consistency line-by-line. 要做到这一点,您需要打开并读取文件,例如使用fgetcsv并逐行检查数据一致性。


You can find a lot of examples on the web. 你可以在网上找到很多例子。

Here are just some: 这里只是一些:

It can be done via MySQL, but by default LOAD DATA INFILE expects a different format than CSV. 它可以通过MySQL完成,但默认情况下,LOAD DATA INFILE需要与CSV不同的格式。 From the documentation: 从文档:

If you specify no FIELDS or LINES clause, the defaults are the same as if you had written this:

FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED BY '\n' STARTING BY ''

The documentation notes, for when dealing with CSV files: 文档说明,用于处理CSV文件时:

LOAD DATA INFILE 'data.txt' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;

Which is an example of dealing with comma separated values enclosed by "" and line-separated by \\r\\n 这是处理由“”括起并用\\ r \\ n换行的逗号分隔值的示例

To use this to import a file, make sure your statement matches the CSV format of your upload files and you can import via this manner. 要使用此文件导入文件,请确保您的语句与上传文件的CSV格式匹配,您可以通过这种方式导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM