Value return when no rows in PDO(PDO 中没有行时返回值)
问题描述
我有一个 PDO 函数:
I have a PDO function:
function(){
$success=$this->query($query, $bindvalues);
return ($success == true) ? $this->stmt->fetch(PDO::FETCH_ASSOC) : false;
}
当我执行返回一行(或更多)的选择查询时,它将返回例如:
When I perform a select query that returns a row (or more), it will return for example:
array(1) { ["Id"]=> string(1) "1" }
当查询失败时(例如,如果我有错误的语法),它将返回 FALSE.
When the query fails (if I have a wrong syntax for example), it will return FALSE.
但如果查询中没有找到任何行,它也会返回 FALSE.
But if no rows are found with the query it also returns FALSE.
因此,查询中有错误且没有行的返回值都将返回 FALSE.这怎么可能?只有在查询中出现错误时我才需要返回 FALSE,例如当没有结果时我需要返回 NULL.我的功能有问题吗?
So the return value with an error in the query and with no rows will both return FALSE. How is that possible? I need to return FALSE only when there is an error in the query, and I need to return NULL for example when there are no results. Is there something wrong in my function?
谢谢!
推荐答案
如果没有找到行 PDO::fetch 返回 false.这是事实.所以改变你的功能:
If no row was found PDO::fetch returns false. This is a fact. So change your function:
function(){
$success = $this->query($query, $bindvalues);
if(!$success) {
//handle error
return false;
}
$rows = $this->stmt->fetch(PDO::FETCH_ASSOC);
return $rows ?: null;
}
这篇关于PDO 中没有行时返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PDO 中没有行时返回值


基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何替换eregi() 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01