简体   繁体   English

PHP MySQL从CSV文件上传中加载数据输入文件

[英]PHP MySQL LOAD DATA INFILE from CSV File Upload

I am trying to learn how to upload new records to MySQL table but seem to be failing so far. 我正在尝试学习如何将新记录上传到MySQL表,但到目前为止似乎还是失败了。 My attempt: 我的尝试:

$uploaded = $_FILES["fileupload"]["name"];
`$try = mysqli_query($connect,"LOAD DATA INFILE IGNORE $uploaded INTO TABLE allrecords");`

I get an error. 我得到一个错误。 It's expected though as the code is a mess. 可以预料,因为代码很乱。 I tried searching in Google but all seem to offer only inserting each records one by one to the database. 我尝试在Google中搜索,但似乎所有人都只提供将每个记录一个一个地插入数据库中的功能。 I used a tag to select the Excel CSV file (exported from Excel) then on the receiving PHP file I use this query. 我使用标签来选择Excel CSV文件(从Excel导出),然后在接收PHP文件中使用此查询。

I use LOAD DATA INFILE IGNORE because I want to upload new records to the database but not include records who's primary key already exist in the database. 我使用LOAD DATA INFILE IGNORE,因为我想将新记录上载到数据库,但不包括数据库中已经存在主键的记录。 Also I'm not sure how to do LOAD DATA INFILE and match each fields. 另外我不确定如何执行LOAD DATA INFILE并匹配每个字段。 Do I need to rename each column names/headers in Excel CSV to match the field names in database? 是否需要重命名Excel CSV中的每个列名称/标题以匹配数据库中的字段名称?

As @drew wisely mentioned in his comments above, you are missing single quotes around the file name in your LOAD DATA statement, which can mess things up. 正如@drew在上面的评论中明智地提到的那样,您在LOAD DATA语句中的文件名周围缺少单引号,这可能会使事情变得混乱。 You may also be missing a few other things which would prevent it from working. 可能还缺少其他一些东西,这会阻止它正常工作。

Try using this PHP code instead: 尝试改用以下PHP代码:

$uploaded = $_FILES["fileupload"]["name"];
`$try = mysqli_query($connect,"LOAD DATA INFILE IGNORE '$uploaded' INTO TABLE allrecords FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY ',,,\r\n'");`

Here is that LOAD DATA command as separate (readable) query: 这是作为单独(可读)查询的LOAD DATA命令:

LOAD DATA INFILE IGNORE '$uploaded'
INTO TABLE allrecords
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY ',,,\r\n'

Note carefully that the double quote in OPTIONALLY ENCLOSED BY has to be escaped so PHP doesn't choke. 仔细注意,在双引号OPTIONALLY ENCLOSED BY转义所以PHP不呛。

And as another aside comment, LOAD DATA is fairly primitive with regard to what it can do handling data. 另外, LOAD DATA在处理数据方面相当原始。 It is intended as a workhorse to bring in raw data to MySQL. 它旨在将原始数据引入MySQL。 For complex filtering and manipulations of your raw data, you are probably better off doing the work in MySQL proper. 对于原始数据的复杂过滤和操作,最好在MySQL适当的地方进行。

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

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