Ace
Ace

Reputation: 845

extract PDO error message

I tried getting error message on connection in PDO but it returns SQLSTATE[HY000] [1045] Access denied for user 'aa'@'localhost' (using password: YES) . along with code and SQLSTATE part. Is there a way to get only Access denied for user 'aa'@'localhost' (using password: YES) part ?

How can i extract part after [1045] so that i can print only error part or error? I'm using:

try {
    $conn = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

} catch(PDOException $e) {
    var_dump($e->getMessage());

}

Thanks guys i found my answer

Upvotes: 0

Views: 651

Answers (2)

Ace
Ace

Reputation: 845

I found my answer

try {
    $conn = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

} catch(PDOException $e) {
    if(strstr($e->getMessage(), 'SQLSTATE[')) {
            preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(), $matches);
           var_dump($matches);
        }

at http://www.php.net/manual/en/class.pdoexception.php#97908

Upvotes: 0

geekInside
geekInside

Reputation: 588

using errorinfo try :

$errorInfo= $db->errorInfo();
$msg= $errorInfo[2];

PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of the following fields:

Element Information 0 SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard). 1 Driver-specific error code. 2 Driver-specific error message.

source :

http://www.php.net/manual/en/pdo.errorinfo.php

Upvotes: 2

Related Questions