Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MySQL error code with PHP

Tags:

php

mysql

pdo

I'm using PHP and PDO to connect to my MySQL database. I configured the PDO connection so that I get any MySQL error thrown as an exception:

$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Now lets suppose I execute a MySQL command that generates an error and I catch it, the error message is this:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'Name' cannot be null

When I use $exception->getCode() it returns 23000, which I think is from PHP or something. How do I get the specific MySQL error (1048) inside a catch block?

like image 582
user937450 Avatar asked Apr 26 '26 10:04

user937450


2 Answers

A PDOException object has a property errorInfo which is a three-element array, the same returned by PDO::errorInfo(). The MySQL error code is element 1.

try {
    . . .
} catch (PDOException $e)
    $errorInfo = $e->errorInfo;
    error_log "MySQL error " . $errorInfo[1] . "\n";
}

PS: Note that just echoing the error is not proper exception handling, I'm just doing that to show how to access the info.

like image 84
Bill Karwin Avatar answered Apr 28 '26 05:04

Bill Karwin


Since you're using PDO, you can refer to here, which provide an excellent description and example on how to get the error info from SQL.

like image 30
viclim Avatar answered Apr 28 '26 05:04

viclim