(PHP 5 >= 5.1.0, PHP 7, PHP 8)
PDOException::getCode — Gets the SQLSTATE error code
Returns the exception code. This is the inherited Exception::getCode(), but unlike in most other exceptions, the code is usually a string.
This function has no parameters.
Returns the SQLSTATE as a five-character
string (for example "42S02" or
"HY000"), see PDO::errorCode().
If the connection fails in PDO::__construct(),
returns the driver-specific error code as an int instead
(for example 1045 for access denied in MySQL).
The code parameter of
Exception::__construct() only accepts an
int, so passing this value to it when rethrowing the error as
a different exception throws a TypeError.
Casting it to int loses information
("HY000" becomes 0).
Pass the original exception as the previous
parameter instead.
Example #1 PDOException::getCode() example
<?php
$pdo = new PDO('sqlite::memory:');
try {
$pdo->query('SELECT * FROM missing_table');
} catch (PDOException $e) {
var_dump($e->getCode());
}
?>The above example will output:
string(5) "HY000"
Example #2 Rethrowing a PDOException
<?php
class DatabaseException extends RuntimeException {}
$pdo = new PDO('sqlite::memory:');
try {
try {
$pdo->query('SELECT * FROM missing_table');
} catch (PDOException $e) {
// Passing $e->getCode() as the code would throw a TypeError
throw new DatabaseException('Query failed', previous: $e);
}
} catch (DatabaseException $e) {
echo $e->getMessage(), ': ', $e->getPrevious()->getCode(), "\n";
}
?>The above example will output:
Query failed: HY000