PHP CSV Upload to Database
Like this blog? Consider exploring one of our sponsored banner ads...
Here is the simplest way I know of to take a CSV (comma separated value) file and upload it to your web site somewhere, and use PHP to slam all the records into a database table. This should only be used “as is” in a controlled environment, as there is no input validation whatsoever, but it is enough to get the point across if you have never done this before. I added the mysql_real_escape_string() function, as someone asked how values containing single and double quotes could be handled with my original CSV upload to database example.
$output = array('Pass' => 0, 'Fail' => 0); ini_set('auto_detect_line_endings',1); $handle = fopen('upload.csv', 'r'); while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) { $val1 = mysql_real_escape_string($data[0]); $val2 = mysql_real_escape_string($data[1]); $val3 = mysql_real_escape_string($data[2]); mysql_query("INSERT INTO `table` (`col1`,`col2`,`col3`) VALUES ('{$val1}','{$val2}','{$val3}')"); $result = (mysql_insert_id() > 0) ? 'Pass' : 'Fail' ; $output[$result]++; } print_r($result);
About this entry
You’re currently reading “PHP CSV Upload to Database,” an entry on BRADINO
- Published:
- 5.29.07 / 5pm
- Category:
- PHP
- Tags:
1 Comment
Jump to comment form | comments rss [?]