php - How to display my own errors instead of default errors using pdo connection?

281

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

441

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;

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

        case ...

        default:
            $message = $e->getMessage(); 
            break;
    }
}
...

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 atPDO::errorCode instead .

http://php.net/manual/en/pdo.errorcode.php

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

Source

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.