sunshinekitty
sunshinekitty

Reputation: 2375

PHP !isset returns true when not set

Firstly, my code:

    $stmt = $pdo->prepare("SELECT id FROM users WHERE
                                        username = :user_email OR
                                        email = :user_email");
        $user_email = $_POST["usernameemail"];
    $stmt->execute(array(
                                    'user_email'=>$user_email
                                    ));
    $account_exist = $stmt->fetch();
    if(!isset($account_exist)) {
        $account_exist_error = '<p style="color:#F00;">Username or Email not found</p>';
    }

$account_exist_error does not return when the query doesn't find anything

I have also tried

if($account_exist === '') {
    ect
}

Neither of these return anything, and other relevant questions are not helping me, $account_exist = '' is set earlier in my code

Upvotes: 0

Views: 93

Answers (3)

The Alpha
The Alpha

Reputation: 146191

You can use

if(!$account_exist)

instead of

if(!isset($account_exist))

Because, it's return values are

TRUE    Success. Data has been fetched
FALSE   Error occurred
NULL    No more rows/data exists or data truncation occurred

In this case false and null both are falsy values and works with ! operator. If you use

f(!isset($account_exist))

Then, it's is always set, because $account_exist contains a value.

Upvotes: 1

Shea
Shea

Reputation: 1950

Normally, empty($var_name) would be more reliable, which will return true for anything null, blank, or undefined. This even includes empty arrays.

However, in this case, you are returning a DB object. Which will always return true for isset, and false for empty. So you are going to want to use the DB object API. In which case, you should use rowCount.

Upvotes: 3

Vitor Villar
Vitor Villar

Reputation: 1925

Try

if ($account_exist == null)

Upvotes: 0

Related Questions