Entry
How can I import a flat file into MySQL?
Mar 13th, 2001 00:45
Andrew Cordery, Nathan Wallace, MySQL New Riders Book
MySQL's LOAD DATA INFILE command allows you to import pretty much any
formatted text file. The syntax is:
LOAD DATA LOCAL INFILE "name_of_file.file_extension" INTO TABLE
name_of_table FIELDS TERMINATED BY "character_to_terminate_fields_with"
ENCLOSED BY "character_to_enclose_fields_with"
For example to import a standard CSV file called help.csv into the
table Help you would enter:
LOAD DATA LOCAL INFILE "help.csv" INTO TABLE Help FIELDS TERMINATED
BY "," ENCLOSED BY "\""
Otherwise you'll probably want to slurp up the file
with the file() operator, split into fields with
explode() or split() -- after trimming newline characters
off the end with chop().
Then assemble INSERT commands and pass them to mysql_query().
I'm not certain if LOAD DATA INFILE works within
a mysql_query() call, although I'd imagine so.