简体   繁体   中英

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. 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. I used a tag to select the Excel CSV file (exported from Excel) then on the receiving PHP file I use this query.

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. Also I'm not sure how to do LOAD DATA INFILE and match each fields. Do I need to rename each column names/headers in Excel CSV to match the field names in database?

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. You may also be missing a few other things which would prevent it from working.

Try using this PHP code instead:

$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 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.

And as another aside comment, LOAD DATA is fairly primitive with regard to what it can do handling data. It is intended as a workhorse to bring in raw data to MySQL. For complex filtering and manipulations of your raw data, you are probably better off doing the work in MySQL proper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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