本文介绍了当PDO中没有行时返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有PDO功能:

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

08-26 07:38
查看更多