Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

php - 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 value although the record already exists in the DB. How do I prevent this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...