PDO Exception and Error Handling
How to handle errors and to check whether the db is connected to or not to PDO?
Explanation
In mysql db, to check whether the database is connected to or not, use the following code:
<?php
$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.
- PDO::ERRMODE_SILENT
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.
- PDO::ERRMODE_WARNING
It throws standard PHP warning, and allows the program to continue execution. It is useful for debugging.
- PDO::ERRMODE_EXCEPTION
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 :
<?php
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
?>