php - How to display my own errors instead of default errors using pdo connection?
I want to display my own errors instead of default errors using pdo connection.The error can be categorized as
1. If database doesn't exist
2. Access Denied
3. Host Name InValid
A simple code of PDO connection is
<?php
$host = 'localhost';
$dbname = 'test';
$user = 'root';
$password = '';
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Now, Can I use the if statements in catch section? If so, How can I achieve my output? I Don't want to usegetMessage()
function.
Thanks
Answer
Solution:
First, use the
param of the constructor to make exceptions being thrown on errors:
Then in your catch block you'll have to analyze the
code
property of the exception:You'll find the list of codes and their meaning in the mysql manual
Answer
Solution:
As @hek2mgl already shown, you first need to tell the driver you want exceptions. To get the actual error you can have a look at the Exceptions code, like so;
You can find a list of SQLSTATE error codes here, http://dev.mysql.com/doc/refman/5.1/en/error-messages-server.html
Depending on the driver you might have to have a look at
PDO::errorCode
instead .http://php.net/manual/en/pdo.errorcode.php