mysqli prepared statement - do not update NULL values

百般思念 提交于 2019-12-14 03:44:23

问题


I have a prepared statement to update several fields. I get the data from a formular, but not all fields are required. So it's possible that some fields are not set. I set them default to NULL. Now I don't want to overwrite the old value by NULL. How can I tell MySql not to Update the value if it's NULL?

$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();

In my case it's the password and random_salt value that could be NULL. It will be very bad to overwrite the password just by NULL ;)


回答1:


You could change your query as follows:

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

It could also be more efficient to check the value of your parameters first, and build the query dynamically, including only fields for which you have a non-null value to update with.




回答2:


You could try this:

$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=?");

the If condition translates to: IF( < YOUR_CONDITION >, < VALUE_IF_TRUE >, < VALUE_IF_FALSE >).




回答3:


Assuming id is PK you can use :

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)
    ...



回答4:


Read your query fields and data carefuly. Set of fields and set of data in bind are not match.

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);

Your bind list has no: password, random_salt, id



来源:https://stackoverflow.com/questions/17102861/mysqli-prepared-statement-do-not-update-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!