user796443
user796443

Reputation:

PDO, check for empty string and don't update if empty

If I run my function edit_profile() without any parameter, then empty strings are written in DB. If $input['email'] is empty for example, I'd like UPDATE not to update this column.

I tried to do:

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

It didn't work, I'm not sure how to do same as above with 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();

Upvotes: 2

Views: 2011

Answers (2)

Marek
Marek

Reputation: 7433

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

Upvotes: 0

Nathan H
Nathan H

Reputation: 49371

Try

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

I'm basically trying to use COALESCE (http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) to use :email only if not null. If it's null, use the old email.

In case :email is empty string and not simply NULL, I've added NULLIF to convert the empty string to NULL ;)

Upvotes: 9

Related Questions