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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With