petenaylor Posted January 23, 2012 Share Posted January 23, 2012 Hi all I am am trying to use the following piece of code to import a CSV file into a mySQL database: $filename = $_FILES['sel_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { mysql_query("INSERT INTO user SET id = '".$userid."', name = '".$data[0]."', email = '".$data[1]."', phone = '".$data[2]."'") or die(mysql_error()); } fclose($handle); It works great except it only imports one line in the CSV file. How do I get it to keep adding the lines into the DB? My CSV looks like this: Pete Naylor,test@mail.com,0800101101 Bob Jones,bob@mail.com,08700123123 Many thanks for for help Pete Quote Link to comment Share on other sites More sharing options...
dzelenika Posted January 23, 2012 Share Posted January 23, 2012 if you try with: $filename = $_FILES['sel_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { print_r($data); mysql_query("INSERT INTO user SET id = '".$userid."', name = '".$data[0]."', email = '".$data[1]."', phone = '".$data[2]."'") or die(mysql_error()); } fclose($handle); what is the output? Quote Link to comment Share on other sites More sharing options...
petenaylor Posted January 23, 2012 Author Share Posted January 23, 2012 Hi there, I get: Array ( [0] => Pete Naylor [1] => test@mail.com [2] => 0800101101; Bob Jones [3] => bob@mail.com [4] => 08700123123; ) Duplicate entry '12' for key 1 Quote Link to comment Share on other sites More sharing options...
dzelenika Posted January 23, 2012 Share Posted January 23, 2012 fegtcsv doesn't recognize your line endings. Which is your server OS and OS of client that created CSV file? Quote Link to comment Share on other sites More sharing options...
petenaylor Posted January 23, 2012 Author Share Posted January 23, 2012 I'm creating the CSV in textedit on a mac and mySQL 5.0.91 with PHP 5 Quote Link to comment Share on other sites More sharing options...
dzelenika Posted January 23, 2012 Share Posted January 23, 2012 add ini_set("auto_detect_line_endings", 1); as 1st line of your script Quote Link to comment Share on other sites More sharing options...
petenaylor Posted January 23, 2012 Author Share Posted January 23, 2012 Brilliant, it worked! Thank you very much! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.