PDO Exception and Error Handling

How to handle errors and to check whether the db is connected to or not to PDO?


In mysql db, to check whether the database is connected to or not, use the following code:
$host = "localhost";
$username = "username";
$password = "password";
$db = "dbname";
// Create connection
$conn = new mysql($host, $db,$username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Connected successfully";

PDO has three error handling modes.


  • This is the default mode. PDO extension highlights the error by using PDO::errorCode() method whereas PDO::errorInfo() method fetches error information on both the statements and database objects.

    PDOStatement::errorCode() - Fetch the error information associated with the last operation on the statements.
    PDOStatement::errorInfo() - Fetch and retrieve the extended error information on the statements and database objects.

  • It throws standard PHP warning, and allows the program to continue execution. It is useful for debugging.


  • It throws PDO exception. This mode is used in most of the situations.

Follow the code given below to check whether the db is connected to PDO

Example :

try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
catch (PDOException $e)
echo $e->getMessage();

PHP Topics

Ask Questions

Ask Question