2014-02-24 86 views
-1

我有一個CSV文件,我想要導入到數據庫中,然後使用省略的列導出相同的數據。我會如何去做這件事?有什麼建議麼?使用PHP腳本將CSV導入到MySQL?

+0

您應該閱讀['LOAD DATA INFILE'](http://dev.mysql.com/doc/refman/5.6/en/load-data.html)上的文檔。 – tadman

+0

如果數據庫僅僅是一個臨時傾倒場,則不是必需的。 'fgetcsv()','array_splice()'和'fputcsv()'應該是你所需要的。 –

+0

我建議使用http://www.ozerov.de/bigdump/,速度要快很多。 –

回答

0
<?php 
    $databasehost = "localhost"; 
    $databasename = "test"; 
    $databasetable = "sample"; 
    $databaseusername="test"; 
    $databasepassword = ""; 
    $fieldseparator = ","; 
    $lineseparator = "\n"; 
    $csvfile = "filename.csv"; 

     if(!file_exists($csvfile)) { 
      die("File not found. Make sure you specified the correct path."); 
     } 

try { 
    $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", 
    $databaseusername, $databasepassword, 
    array(
     PDO::MYSQL_ATTR_LOCAL_INFILE => true, 
     PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION 
     ) 
    ); 
} catch (PDOException $e) { 
die("database connection failed: ".$e->getMessage()); 
} 

$affectedRows = $pdo->exec(" 
    LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable` 
     FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." 
     LINES TERMINATED BY ".$pdo->quote($lineseparator)); 

echo "Loaded a total of $affectedRows records from this csv file.\n"; 

?>