PHP CSV Upload to Database

Here is the simplest way I know of to take a CSV (comma separated value) file and upload it through a form, catch it with PHP and 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.

PHP:
  1. <?php
  2.  
  3. //CHECK THAT THE FILE WAS UPLOADED
  4. if (is_uploaded_file($_FILES['file']['tmp_name'])){
  5.    
  6.     //THIS WILL HELP IF ANY CSV FILES CREATED BY A MAC
  7.     ini_set('auto_detect_line_endings',1);
  8.    
  9.     //SPIN THROUGH THE RECORDS
  10.     $handle = fopen($_FILES['file']['tmp_name'], "r");
  11.     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
  12.    
  13.         //INSERT A RCORD TO THE DATABASE
  14.         mysql_query("INSERT INTO `table` (`field1`,`field2`,`field3`) VALUES ('{$data[0]}','{$data[1]}','{$data[2]}')");
  15.    
  16.     }
  17.    
  18. }
  19.    
  20. ?>

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank

Home | PHP | PHP CSV Upload to Database