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

$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.





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;

} catch (PDOException $e) {
    switch ($e->getCode()) {
        case 1041: //  Error: 1041 SQLSTATE: HY000 (ER_OUT_OF_RESOURCES)
            $message = 'MySQL is out of resources!';

        case ...

            $message = $e->getMessage(); 

You can find a list of SQLSTATE error codes here,

Depending on the driver you might have to have a look atPDO::errorCode instead .

People are also looking for solutions to the problem: unix - PHP CronJob doesn't work


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.