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...
PDOStatement::fetchAll()
returns an array of arrays. To check for a record, tryif (count($res) == 0) { // no records found }
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);
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 thePDO::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 :).
精彩评论