Get MySQL error code with PHP

Solution:1

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.

Solution:2

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.