Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 446
Jordy Avatar asked Aug 30 '13 10:08

Jordy


People also ask

Which PDO function would you use to count no of rows returned from a table?

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

What does PDO fetchAll return?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

What is returned by the exec () method of the PDO class?

Return Values ¶ PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0 . This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

How fetch data from database in PHP and display PDO?

Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.


1 Answers

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;
}
like image 57
Tobias Golbs Avatar answered Oct 19 '22 22:10

Tobias Golbs