开发者

check when PDO Fetch select statement returns null

I have the following code:

  $check = $dbh->prepare("SELECT * FROM BetaTesterList WHERE EMAIL = ?");
                $check->execute(array($email));
                $res = $check->fetchAll();

                if (!($res['EMAIL'])){
                        $stmt = $dbh->prepare("INSERT INTO BetaTesterList(EMAIL) VALUES (?)");
                        $stmt->execute(array($email));
                } else {
                        $return['message'] = 'exists';
                }

However this still inserts the val开发者_运维问答ue although the record already exists in the DB. How do I prevent this?


Couple of things here...

  1. PDOStatement::fetchAll() returns an array of arrays. To check for a record, try

    if (count($res) == 0) {
        // no records found
    }
    
  2. Turn on E_NOTICE errors. You would have known that $res['EMAIL'] was an undefined index. At the top of your script...

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);
    
  3. I'd recommend creating a unique constraint on your EMAIL column. That way, you would not be able to insert a duplicate record. If one was attempted, PDO would trigger an error or throw an exception, depending on how you configure the PDO::ATTR_ERRMODE attribute (see http://php.net/manual/en/pdo.setattribute.php)

    If you're not inclined to do so, consider using this query instead...

    $check = $dbh->prepare("SELECT COUNT(1) FROM BetaTesterList WHERE EMAIL = ?");
    $check->execute(array($email));
    $count = $check->fetchColumn();
    
    if ($count == 0) {
        // no records found
    } else {
        // record exists
    }
    


$res should look something like this:

array (
    [0] => array (
        [column1] => value,
        [email] => value
    ),
    [1] => array (
        [column1] => value,
        [email] => value
    ),
    [2] => array (
        [column1] => value,
        [email] => value
    )
)

Therefore, if(!($res['email')) will always evaluate to true because $res['email'] is undefined (null, I suppose) and it is negated. So, negation of a negation = true :).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜