您必須檢查每個值,看它是否是空白的,如果是這樣,修改您的查詢字符串從SET
條款刪除該字段。
事情是這樣的:
<?php
$set = array();
// make sure the user doesn't attempt to POST a column that doesn't exist in our table,
// which will lead to a SQL error, or worse, allow the user to run custom SQL.
$columns = array('value1', 'value2');
foreach ($_POST as $key=>$value) {
if (in_array($key, $columns) && $value != '') {
$set[] = $key ." = '". mysql_real_escape_string($value) ."'";
}
}
if (!empty($set)) {
$query = "UPDATE table SET ". implode(', ', $set) ." WHERE `key` = '". mysql_real_escape_string($_POST['key']) ."'";
}
還要注意我用mysql_real_escape_string()
。這是爲了防止SQL注入。我不知道你使用的是什麼MySQL庫,但是你應該使用適當的消毒方法來處理你正在使用的任何東西。實際上,您不應該使用常規的mysql_*
庫,因爲它已被棄用。相反,我會推薦PDO。
我看不出這會如何工作,而不是沒有關鍵字'鍵'沒有在反引號中包裝 - http://dev.mysql.com/doc/refman/5.5/en/reserved-words .html – 2014-10-18 01:54:00
'update table_name set value1 ='value1'<>''的情況,然後'$ value1'else else value1 end where ...'並且爲value2添加相同的值。 – 2014-10-18 02:00:11
你不能只用PHP開始編寫SQL,你需要在PHP的'mysqli_query()'查詢函數中完成。 – 2014-10-18 02:12:58