I have an issue with the exception handling of PDO::exec. In the following example I have an existing PDO connection and want to execute a sql-statement. This works quite well so far, but it does not work if I hand over a faulty query. In this case I want it to process the specified exception, but the program stops with a fatal error without the exception block ever executed. Here is the erroneous code snippet:
try{
$connection->exec( $query );
} catch( PDOException $err ) {
echo "caught
";
echo $err->getMessage();
}
This results in the error Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
and the program aborts.
I have also tried:
if( $connnection->exec( $query ) === false ) {
echo "Failure
";
} else {
echo "Success
";
}
which was unfortunately equally unsuccessful. What is the problem here? Are there perhaps any best practice examples (I haven't found any so far)?
Most likely it's namespace or xdebug to blame for this uncaught exception.
Are there perhaps any best practice examples
Sure.
Do not use exec().
Do not wrap your queries in try-catch unless you're doing it only once, in a wrapper and going to re-throw it.
and the program aborts.
that's exactly what a good program ought to do when encountered with a faulty query.