Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO: Displaying errors

Tags:

php

pdo

Do I need to use the try and catch block to display errors with PHP's PDO extension?

For example, with mysql you can usally do something like:

if ( ! $query)
{
    die('Oh noes!');
}
like image 374
user1518061 Avatar asked Jul 13 '26 21:07

user1518061


2 Answers

You can choose what PDO does with errors via PDO::ATTR_ERRMODE:

$pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // Raise E_WARNING.
$pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // Sets error codes.
// or
$pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // throws exception
like image 117
DavidS Avatar answered Jul 15 '26 12:07

DavidS


PDO by default supports it's own Exception Class, PDOException.

There should be no reason why you cannot use:

try{
    $query = $db->prepare(...);
    if( !$query ){
        throw new Exception('Query Failed');
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

The reason I only catch Exception is because PDOException is a child of Exception. Catching the Parent will catch ALL children.

like image 45
Mike Mackintosh Avatar answered Jul 15 '26 12:07

Mike Mackintosh