I have this block of code:
try {
$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_database, $db_user, $db_pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$dbh->prepare('DELECT userID FROM tblusers');
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
When I step through the code using the debugger in my IDE, it never enters into the catch
block even though I have an error in my prepare
statement.
What am I doing wrong?
I'm new to PDO and try/catch blocks so bear with me here if this is a dumb question!
PDO_mysql uses emulated prepared statements by default (performance reasons), so prepare will not throw an exception. PDOStatement::execute
will though.
You can turn emmulation off by doing as jonnyynnoj mentions, but i find catching an exception on execution is usually good enough.
Try adding $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.
try / catch will only catch exceptions. Other errors (Parse errors, runtime errors, etc) won't execute the catch-block.
In your case only exceptions of type "PDOException" get caught, everything else probably gets displayed or logged (depending on your error reporting directives in php.ini).
What's being displayed as error?