The PHP PDOException
is a runtime exception that occurs when something goes wrong while using the PDO (PHP Data Objects) class or its related extensions. For example, this exception can occur while handling database connections or queries.
What Causes PDOException
PHP Data Objects (PDO) are a collection of APIs that are used to access and work with databases. The PDOException
is thrown anytime an issue occurs while using the PDO interface. Common situations where this exception can occur are:
- Attempting to connect to a database e.g. entering an incorrect password for the database connection.
- Issuing an SQL statement e.g. missing database table, invalid SQL statement.
PDOException Example
Here’s an example of a PHP PDOException
thrown when facing issues connecting to a database using the PDO interface:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
?>
In the above example, the PDO class is used to establish a connection to a database. Since the database connection parameters are incorrect, running the above code throws a PDOException
:
PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused in main.php:2
Stack trace:
#0 main.php(2): PDO->__construct('mysql:host=loca...', 'user', 'pass')
#1 {main}
thrown in main.php on line 2
How to Handle PDOException
The PDOException
can be caught and handled using a try-catch block. The try
block should contain the lines of code that can throw the exception and the catch
block should catch and handle the PDOException
appropriately. The message associated with the exception can be retrieved using the Exception::getMessage
method on the PDOException
object.
Using the above approach, the previous example can be updated to handle the error:
<?php
try {
$dbh = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
} catch (PDOException $e) {
print "Error: " . $e->getMessage();
}
?>
Here, a check is performed for the PDOException
using the try-catch block. When the above code is executed, the catch
block catches the PDOException
and handles it, producing the following output:
Error: SQLSTATE[HY000] [2002] Connection refused
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing PHP errors easier than ever. Try it today!