faqts : Computers : Programming : Languages : PHP : Database Backed Sites : MySQL

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

61 of 89 people (69%) answered Yes
Recently 8 of 10 people (80%) answered Yes

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.