Using PHP to import CSV data into mySQL [duplicate]
Possible Duplicate:
How to import csv files selected by user to database
update i now have the fgetcsv() function working and reading the CSV file correctly (displaying the right output, # of fields, etc) so where do i slip in the mysql_query("INSERT....."); into the equation?
For reference: mySQL is running on DreamHost, but on a separate server from my DreamHost web hosting, and i do not have permission to do a LOAD DATA INFILE. I'm not planning to change hosting companies.
I am very new to both PHP and mySQL, and learning hands-on. I've looked at a lot of answers on here, but most suggest using LOAD DATA INFILE, which I cannot use. I can upload and import the CSV in question via phpMyAdmin successfully, and when i attempt to upload/import it via a PHP script, it won't work (because of the permissions issue thru DreamHost).
With my application, users will be uploading structured lists in CSV form. it's kind of the crux of the entire app. due to that开发者_运维技巧 permissions issue, it looks like i'll need to read from the uploaded file line-by-line and do an INSERT for each line.
I have literally no idea where to start here. this script will run once the user has selected their file and pressed upload. it moves the file to the appropriate directory and stores the full file's path in $path.
You will want to look into fgetcsv(). Funny enough, as of this post, the first comment is a function doing exactly what you have outlined above.
http://php.net/manual/en/function.fgetcsv.php
You're right, you should parse each line. This will also give you the opportunity to validate the data so users can't use SQL injection.
You can use:
http://code.google.com/p/php-csv-parser/
I use dreamhost for some things too. But when you're ready to grow a bit, graduate to AWS.
One further note. I know that CSV is popular, but if there's any chance you can constrain your users to upload XML (or json), it'll make your job easier when parsing. This, of course, isn't always feasible if it's open to the public, as people have trouble with XML. But if the source of data is a professional one, I'd highly recommend using XML or JSON over CSV.
If you really can't use the LOAD DATA INFILE MySQL function, you will have to import the CSV file using php. The easiest way is probably to use the PHP fgetcsv() function.
精彩评论