Re: csv inssue
| From: | Jim Grill | Date: | Fri, 24 Sep 2004 14:02:38 +0000 |
| Subject: | Re: csv inssue | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-197781@lists.php.net to get a copy of this message | ||
> I was curious if anyone could help me. I need to write an insert to take
> data from a csv file to put into a MySQL db. I am not sure know to parse
out
> 5 items of the string at a time i.e. (1,2,3,4,5,1,2,3,4,5,1...etc) so that
> the five putted items get inserted everytime. Like:
>
> "insert into products (item,price,rate,name,desc) values (1,2,3,4,5)"
>
> Then on to the next one and so forth.
>
> I am already parsing the file, but not sure if it needs to go into an
array
> or set to vars then done in a loop.
>
> Please help!
This is not really a PHP answer; However I feel your problem is not best
solved with PHP.
If your csv file is a standard csv file you don't need PHP to parse it.
MySQL is capable of importing csv files on its own. Take a look at
http://dev.mysql.com/doc/mysql/en/LOAD_DATA.html
Example:
$query = 'LOAD DATA INFILE "/path/to/your/file.csv" INTO TABLE mytable';
Even if your file is not of a standard csv format you can specify what your
fields and lines are terminated by, enclosed by, escaped by, starting by,
etc, etc.
When uploading a CSV file exported from MS excel:
$query = 'LOAD DATA INFILE "/path/to/your/file.csv" INTO TABLE mytable
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY """" LINES TERMINATED
BY
"\\r\\n"';
Very versatile. Make that lazy MySQL server pull its weight! Let PHP handle
the really complicated stuff :-)
Jim Grill