gpt4 book ai didi

php - PDO,检查空字符串,如果为空则不更新

转载 作者:行者123 更新时间:2023-11-29 03:52:22 25 4
gpt4 key购买 nike

如果我在没有任何参数的情况下运行我的函数 edit_profile(),那么空字符串将写入 DB。例如,如果 $input['email'] 为空,我希望 UPDATE 不要更新此列。

我尝试过:

SET email = IF(LENGTH(:email)=0, email, :email),

它没有用,我不确定如何用 PDO 做同样的事情。

function edit_profile($input) {
//
$user_id = 1;
//
try {
//

$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare('UPDATE users SET
email = :email,
password = :password,
name_surname = :name_surname,
age = :age,
sex = :sex,
education = :education,
avatar = :avatar
WHERE id = :id');


$stmt->execute(array(
':id' => $user_id,
':email' => $input['email'],
':password' => $input['password'],
':name_surname' => $input['name_surname'],
':age' => $input['age'],
':sex' => $input['sex'],
':education' => $input['education'],
':avatar' => $input['avatar']
));


echo $stmt->rowCount(); // 1
//
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//
}
edit_profile();

最佳答案

尝试

UPDATE users SET
email = COALESCE(NULLIF(:email, ''),email),
password = :password,
name_surname = :name_surname,
age = :age,
sex = :sex,
education = :education,
avatar = :avatar
WHERE id = :id

我基本上是在尝试使用 COALESCE ( http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce ) 来使用 :email 仅当不为空时。如果为空,则使用旧的 email

如果 :email 是空字符串而不是简单的 NULL,我添加了 NULLIF 将空字符串转换为 ;)

关于php - PDO,检查空字符串,如果为空则不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19517543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com