php8.5
Home/ Manual/ pdo / pdoexception/ PDOException::getCode

PDOException::getCode

PHP function Edit on GitHub ✎

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Gets the SQLSTATE error code

Description

PDOException::getCode(): int|string

Returns the exception code. This is the inherited Exception::getCode, but unlike in most other exceptions, the code is usually a string.

Parameters Parameters

Return Values

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).

Caution

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.

Examples

PDOException::getCode example

php
<?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:

output
string(5) "HY000"

Rethrowing a PDOException

php
<?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:

output
Query failed: HY000

See Also

  • Exception::getCode
  • Exception::getPrevious
  • PDO::errorCode
  • PDOStatement::errorCode
  • PDO::errorInfo

Source: reference/pdo/pdoexception/getcode.xml · from the official PHP manual (php/doc-en)