PHP INSERT ON DUPLICATE KEY IGNORE添加空值?
我正在使用下面的代码来从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个手动字段中的值并保持数据完好?
千恩万谢
如果你告诉MySQL使用空值更新领域,它会,所以只要我能看到你有三种选择(在我的优先顺序...):
- 请确保表单中的所有值都使用数据库中的值加载。如果你不想显示所有的值,你可以使用隐藏的输入;
- 动态构建您的sql语句的第二部分(在
ON DUPLICATE KEY UPDATE
之后);只有在变量不为空时才添加字段; - 修改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.
或者,如果你把所有的字段数组,你可以循环,将字符串添加到一个新的数组和崩溃。
很好的信息:)我将如何编码您的第二个选项? – 2013-02-19 21:10:50
@Stephen Jackson查看我的编辑。 – jeroen 2013-02-19 21:14:32
检查'插入忽略':http://stackoverflow.com/questions/2366813/on-duplicate-key-ignore – complex857 2013-02-19 20:47:57