Search code examples
phpmysqlpdoexceptionfetch

PHP PDO fetch returns FALSE when no records found AND on failure


The PDO method fetch() returns the value FALSE both when no records are found AND on failure (e.g. when something goes wrong regarding the database access).

I need to be able to differentiate between the two situations and to handle each one in the corresponding manner:

  • to display a message to the user when no records are found and
  • to throw an exception on failure.

So, my question: is there a way to handle the result in a proper manner?

Thank you for your time.

P.S.: I would have expected to receive an empty array as result, when no records are found, and the value FALSE when something goes wrong. Like in the case of fetchAll() method.


UPDATE:

The method PdoStatement::fetch throws exceptions on failure, instead of FALSE. Such a case is demonstrated in my answer:

In conclusion, as @pucky124 already said, the differentiation is easy so achieve:

  • PDOStatement::fetch returns FALSE if no records are found.
  • PDOStatement::fetch throws exceptions on failure.

Solution

  • This is what PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION is for. Use it like this:

    $pdo = new PDO(
                'mysql:host=localhost;port=3306;dbname=mydb;charset=utf8'
                , 'user'
                , 'pass'
                , [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ]
        );
    

    When used this way errors actually get thrown as exceptions. This means that should an error occur with fetch (or other methods using this pdo object) an exception will be thrown and the method won't actually return at all. This is a very effective way of handling errors in PDO. Now you know that if fetch returns a value no errors occured and therefore if it is false then the query returned no records.