问题描述
我有一个 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 中没有行时返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!