I have currently switched to using PDO but am having trouble in handling the exceptions. The connection is correct and queries work perfectly, but when I put in a deliberate mistake the error is not handled as I would expect.
I have changed the name of the table in my query to a table that does not exist. From the code seen below, I would expect the page to print out ‘Database Error’ but instead get the horrible orange error saying…
‘Uncaught exception ‘PDOException’ with message ‘SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test.post’ doesn’t exist’ in C:\wamp\www\website\functions.php on line 46′
Here is the code when connecting the database…
$hostname = 'localhost';
$username = '';
$password = '';
try{
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print ("Database Error");
}
Am I making a mistake or is there a different way to handle PDO errors?
After connecting, you need to set the error handling:
Edit: Note that the exception gets caught at the place it is thrown, so you need to put a
trycatchblock around the query, the one you use when connecting only catches exceptions there (if any, see @Crontab’s comment).