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

时间:2013-10-22 12:12:18

标签: php mysql pdo

如果我在没有任何参数的情况下运行我的函数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();

2 个答案:

答案 0 :(得分:9)

尝试

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而不是null。如果它为null,请使用旧的email

如果:email为空字符串,而不仅仅是NULL,我已添加NULLIF将空字符串转换为NULL;)

答案 1 :(得分:1)

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

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