mysqli预处理语句 - 不更新NULL值

时间:2013-06-14 07:02:35

标签: php mysql mysqli prepared-statement

我有一份准备好的声明来更新几个字段。我从公式中获取数据,但并非所有字段都是必需的。因此可能没有设置某些字段。我将它们设置为NULL。现在我不想用NULL覆盖旧值。如果值为NULL,我怎么能告诉MySql不要更新值?

$insert_stmt = $mysqli->prepare("
UPDATE members SET username=?, email=?,  $password=?, $random_salt=?, level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?
");
$insert_stmt->bind_param('ssssissss', $username, $email, $password, $random_salt, $level, $customerID, $firstname, $surname, $phone);
$insert_stmt->execute();

在我的例子中,密码和random_salt值可能为NULL。仅用NULL覆盖密码是非常糟糕的;)

4 个答案:

答案 0 :(得分:4)

您可以按如下方式更改查询:

UPDATE members SET
    username = IFNULL(?, username),
    email = IFNULL(?, email) -- and so on for all fields
WHERE...

首先检查参数值并动态构建查询也可能更有效,包括只有要更新的非空值的字段。

答案 1 :(得分:1)

你可以试试这个:

$insert_stmt = $mysqli->prepare("UPDATE members SET username=?, email=?,  password=IF(LENGTH('?')=0, password, '?'), random_salt=IF(LENGTH('?')=0, random_salt, '?'), level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?");

If条件转换为:     IF(< YOUR_CONDITION>,< VALUE_IF_TRUE>,< VALUE_IF_FALSE>)。

答案 2 :(得分:0)

仔细阅读您的查询字段和数据。绑定中的字段集和数据集不匹配。

UPDATE members SET username=?, email=?,  $password=?, $random_salt=?, level=?, customerID=?, name=?, surname=?, phone=?, quantities=? WHERE id=?

$insert_stmt->bind_param('ssssissss', $username, $email, $level, $customerID, $firstname, $surname, $phone);

您的绑定列表没有:password,random_salt,id

答案 3 :(得分:0)

假设id是PK,你可以使用:

INSERT INTO members (
    id,
    username,
    email,
    password,
    random_salt,
    level,
    customerID,
    name,
    surname,
    phone,
    quantities
) VALUES (
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?,
    ?
)   ON DUPLICATE KEY UPDATE
    username = IF(username <> '',VALUES(username),username),
    email = IF(email <> '',VALUES(email),email),
    password = IF(password <> '',VALUES(password),password)
    ...