简体   繁体   中英

PHP - Upload CSV file and import to database, where table doesnt exist

I need to create a PHP file that will take a text file containing a LOT of data, and import it into a MySQL database.

I know I can do this by opening the file, parsing it, and using individual commands per line to insert the data.

But I want to know if there is a way to do this if the MySQL table doesn't exist first.

I am trying to automate the process as much as possible, to remove time and potential human error.

So, is it possible to specify a text file (it is a CSV file, but the data is separated by '|' instead of commas) in PHP, and have the PHP script first create the MySQL table, and then import the full data file into that table?

The first line of the text file will always contain the column names.

I know I could do this by opening the file, taking the first line, using that to create a table, and then going back and looping through the file again, inserting data a line at a time - but I want to know if there is a quicker and more efficient way of handling the files than that!

The files are really large, so the method needs to be as efficient as possible, and I feel that there may be a command that I am not aware of??

http://dev.mysql.com/doc/refman/5.0/en/mysqlimport.html

Like

mysqlimport  --ignore-lines=1 --fields-terminated-by=,
--columns='ID,foo,bar' --local -u root -p
Database /path/to/csvfile/TableName.csv 

For creating the actual table, you should just use a query for that before you import the data. With the query you can specify about anything to create the table, columns and datatypes etc.

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