check when PDO Fetch select statement returns null(检查 PDO Fetch select 语句何时返回 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查 PDO Fetch select 语句何时返回 null
基础教程推荐
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01