PDOException
PHPERRORNotableDatabase

Database error via PDO

Quick Answer

Set PDO error mode to ERRMODE_EXCEPTION and log $e->getCode() (SQLSTATE) alongside the message.

What this means

Thrown by PDO when a database operation fails — query errors, connection failures, constraint violations. Extends RuntimeException and carries a SQLSTATE code.

Why it happens
  1. 1SQL syntax error in a prepared statement template
  2. 2Unique constraint violation on INSERT

Fix

Enable exceptions and inspect SQLSTATE

Enable exceptions and inspect SQLSTATE
$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

try {
    $pdo->exec($sql);
} catch (\PDOException $e) {
    $state = $e->getCode(); // SQLSTATE e.g. "23000"
    if ($state === '23000') {
        throw new DuplicateEntryException("Duplicate key", 0, $e);
    }
    throw $e;
}

Why this works

ERRMODE_EXCEPTION converts all PDO errors to exceptions; SQLSTATE "23000" indicates a constraint violation.

Code examples
getCode() for SQLSTATEphp
catch (\PDOException $e) {
    // $e->getCode() returns SQLSTATE string like '23000'
    // $e->errorInfo[1] returns driver-specific code
    logger()->error('DB error', ['sql_state' => $e->getCode()]);
}
Check duplicate keyphp
try {
    $stmt->execute([$email]);
} catch (\PDOException $e) {
    if (str_starts_with($e->getCode(), '23')) {
        throw new \DomainException("Email already registered");
    }
    throw $e;
}

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PHP errors