2014-09-20 78 views
0

嗨,你可以看到我有這個PHP腳本:截斷表中所有MySQL列除了第一

<?php 
    $databasehost = "localhost"; 
    $databasename = ""; 
    $databasetable = ""; 
    $databaseusername=""; 
    $databasepassword = ""; 
    $fieldseparator = ","; 
    $lineseparator = "\n"; 
    $enclosedbyquote = '"'; 
    $csvfile = "file.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()); 
    } 

    $pdo->exec("TRUNCATE TABLE `$databasetable`"); 

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

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

    ?> 

現在你可以看到這是CSV文件導入到我的數據庫和截斷整SQL表。

我的問題是如何阻止表的第一列受到導入的影響?我將使用第一列作爲ID,任何想法我怎麼能做到這一點?

謝謝

回答

0

簡單。而不是:

TRUNCATE TABLE `$databasetable` 

使用:

UPDATE `$databasetable` SET colB = '', colC = '', colD = '', colE = ''; 

其中可樂要保留列。如果使用NULL字段,請更改爲:

UPDATE `$databasetable` SET colB = NULL; #etc.