2013-02-19 169 views
0

我正在使用下面的代碼來從xml文件更新數據庫,一切都按預期工作,但現在我不得不向表中添加更多的字段並通過html表單手動更新數據。PHP INSERT ON DUPLICATE KEY IGNORE添加空值?

當我運行窗體時,我可以將數據插入到「afk」和「備註」字段中,但在運行以下查詢時,它將清空這些字段。

$insert = "INSERT INTO `ecmt_memberlist` (characterID,name,startDateTime,baseID,base,title,logonDateTime,logoffDateTime,locationID,location,shipTypeID,shipType,roles,grantableRoles, last_modified) VALUES('$characterID','$name','$startDateTime','$baseID','$base','$title','$logonDateTime','$logoffDateTime','$locationID','$location','$shipTypeID','$shipType','$roles','$grantableRoles','$modifiedTS') ON DUPLICATE KEY UPDATE 
name='$name', 
startDateTime='$startDateTime', 
baseID='$baseID', 
base='$base', 
title='$title', 
logonDateTime='$logonDateTime', 
logoffDateTime='$logoffDateTime', 
locationID='$locationID', 
location='$location', 
shipTypeID='$shipTypeID', 
shipType='$shipType', 
roles='$roles', 
grantableRoles='$grantableRoles', 
last_modified = '$modifiedTS'"; 

是否有可能告訴查詢忽略已存儲在額外2個手動字段中的值並保持數據完好?

千恩萬謝

+0

檢查'插入忽略':http://stackoverflow.com/questions/2366813/on-duplicate-key-ignore – complex857 2013-02-19 20:47:57

回答

0

如果你告訴MySQL使用空值更新領域,它會,所以只要我能看到你有三種選擇(在我的優先順序...):

  1. 請確保表單中的所有值都使用數據庫中的值加載。如果你不想顯示所有的值,你可以使用隱藏的輸入;
  2. 動態構建您的sql語句的第二部分(在ON DUPLICATE KEY UPDATE之後);只有在變量不爲空時才添加字段;
  3. 修改sql語句的第二部分(在ON DUPLICATE KEY UPDATE之後)只更新特定數量的字段。我不會真的推薦這個。

順便說一句,我還建議使用帶有綁定變量的準備語句以避免sql注入問題。

編輯:第二種選擇看起來是這樣的:

$insert = "INSERT INTO `ecmt_memberlist` (characterID,name,startDateTime,baseID,base,title,logonDateTime,logoffDateTime,locationID,location,shipTypeID,shipType,roles,grantableRoles, last_modified) VALUES('$characterID','$name','$startDateTime','$baseID','$base','$title','$logonDateTime','$logoffDateTime','$locationID','$location','$shipTypeID','$shipType','$roles','$grantableRoles','$modifiedTS') ON DUPLICATE KEY UPDATE 
      name='$name'"; 
if (!empty($startDateTime)) 
{ 
    $insert .= ", startDateTime='$startDateTime'"; 
} 
// etc. 

或者,如果你把所有的字段數組,你可以循環,將字符串添加到一個新的數組和崩潰。

+0

很好的信息:)我將如何編碼您的第二個選項? – 2013-02-19 21:10:50

+0

@Stephen Jackson查看我的編輯。 – jeroen 2013-02-19 21:14:32

相關問題