Powered By

Need php script to import csv/excel file into Mysql






Using a script to parse and import the file


If you need to take a csv or other delimited data file and import it INTO MySQL, here is a php script that can do it for you:








$connection = mysql_connect("localhost", "test", "test") or die ("Unable to connect to server");
 $db = mysql_select_db("test", $connection) or die ("Unable to select database");

 // first get a mysql connection as per the FAQ

 $fcontents = file ('./spreadsheet.xls');
 // expects the csv file to be in the same dir as this script


  for($i=0; $i<sizeof($fcontents); $i++) { 
        $line = trim($fcontents[$i]); 
  $arr = explode("\t", $line);
  //if your data is comma separated  instead of tab separated, 
  // change the '\t' above to ','

  $sql = "insert into TABLENAME values ('".implode("','", $arr) ."')";
  mysql_query($sql);
  echo $sql ."\n";
   if(mysql_error()) {
    echo mysql_error() ."\n";
   }
 }
?>








And you can get the source from here




Get It and enjoy....

Note: 
Upload a spreadsheet file into the same directory as this script. Then you edit this script to put in the correct table name instead of "TABLENAME".





Related Posts by Categories