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 ( ! $q
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.
If you don't want to use a try catch statement, you still can use this kind of code :
$query = $db->prepare("SELECT * FROM table");
if(!$query->execute()) {
print_r($query->errorInfo());
}
public static function qry($sql) {
try {
$statement = $db_handle->prepare($sql);
$retval = $statement->execute();
if($statement->rowCount() >= 1) {
//do something
}else {
$errors = $statement->errorInfo();
echo $errors[2] . ", " . $errors[1] . " ," . $errors[0];
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
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