Value return when no rows in PDO

こ雲淡風輕ζ 提交于 2020-01-03 08:39:09

问题


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" }

When the query fails (if I have a wrong syntax for example), it will return FALSE.

But if no rows are found with the query it also returns FALSE.

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?

Thanks!


回答1:


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;
}



回答2:


Here you go

function fetchRow($query, $bindvalues)
{
    $stmt = $this->query($query, $bindvalues);
    return $stmt->fetch();
}


来源:https://stackoverflow.com/questions/18530267/value-return-when-no-rows-in-pdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!