2

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

2 回答 2

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仅在不为空时使用。如果为空,请使用旧的email.

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

于 2013-10-22T12:16:55.697 回答
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']
));
于 2013-10-22T12:32:16.917 回答