检查PDO Fetch select语句何时返回null [英] check when PDO Fetch select statement returns null
问题描述
我有以下代码:
$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?
推荐答案
这里的事物……
-
PDOStatement::fetchAll()
返回一个数组数组.要检查记录,请尝试
PDOStatement::fetchAll()
returns an array of arrays. To check for a record, try
if (count($res) == 0) {
// no records found
}
打开E_NOTICE
错误.您会知道$res['EMAIL']
是未定义的索引.在脚本顶部...
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);
我建议在您的EMAIL
列上创建一个唯一约束.这样,您将无法插入重复的记录.如果尝试这样做,则PDO将触发错误或引发异常,具体取决于您配置PDO::ATTR_ERRMODE
属性的方式(请参见 http://php.net/manual/en/pdo.setattribute.php )
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
}
这篇关于检查PDO Fetch select语句何时返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!