Page 1 of 1

importing a csv file

Posted: Mon May 12, 2008 8:12 am
by kevrelland
hi
i know it is possible to take a csv file and import it to a mysql db via php
but my problem is that my order of data does not match the order of the fields of the db
i know i can do this with navicat, but i wanted to build an online solution

So what i want to know is, can i set the order that the data is imported in to the db with php?
and if you could give me some pointers or direction on where to look.

Cheers
Kevin

Re: importing a csv file

Posted: Mon May 12, 2008 6:07 pm
by Eran
The thing you need to be concerned with is matching the CSV field names to the field names of your db table. You can get the structure of all the rows from the first non-empty row in the CSV file which should contain the field names.
Use something like fgetcsv() to parse it into an array of ordered field names and build your insertion data format from there.

Re: importing a csv file

Posted: Mon May 12, 2008 6:38 pm
by Christopher
You can specify the order of the columns in both the INSERT and LOAD DATA INFILE statements.

Re: importing a csv file

Posted: Tue May 13, 2008 2:30 am
by kevrelland
cheers for that i'll start building my app now
and i'll let you know how it goes
kev

Re: importing a csv file

Posted: Wed May 14, 2008 3:37 am
by kevrelland
i have a new question in relation to this problem,

I need to delete all the data in the table before the new data is inserted is this possible
Cheers
Kevin

Re: importing a csv file

Posted: Wed May 14, 2008 11:46 am
by LBmtb
Use mysql's TRUNCATE statement to clear out the table before importing new stuff in.