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
				
        
 
            
        - 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
 - 覆盖 Magento 社区模块控制器的问题 2022-01-01
 - openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
 - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - PHP - if 语句中的倒序 2021-01-01
 - 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
 - 如何在 Symfony2 中正确使用 webSockets 2021-01-01
 - PHP foreach() 与数组中的数组? 2022-01-01
 - 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
 - Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
 
