check when PDO Fetch select statement returns null

后端 未结 2 1782
甜味超标
甜味超标 2020-12-11 08:43

I have the following code:

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


        
相关标签:
2条回答
  • 2020-12-11 09:17

    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
      }
      
    0 讨论(0)
  • 2020-12-11 09:32

    $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 讨论(0)
提交回复
热议问题