Jordy
Jordy

Reputation: 4809

Value return when no rows in 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" }

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!

Upvotes: 9

Views: 7274

Answers (2)

Tobias Golbs
Tobias Golbs

Reputation: 4616

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

Upvotes: 13

Your Common Sense
Your Common Sense

Reputation: 157839

Here you go

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

Upvotes: 0

Related Questions