PHP MySQL Error Handling

Handle database errors and exceptions properly

MySQLi Error Handling

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); # enable error reporting
try { # try block
    $conn = new mysqli("localhost", "user", "pass", "db"); # connect
} catch (Exception $e) { # catch exception
    error_log($e->getMessage()); # log error
    die("Database error occurred"); # user-friendly message
}

Check Query Errors

$result = $conn->query($sql); # execute query
if (!$result) { # check for failure
    echo "Error: " . $conn->error; # show error message
    echo "Error code: " . $conn->errno; # show error number
}

PDO Error Modes

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # throw exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); # trigger warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); # silent mode

PDO Try-Catch

try { # error handling
    $stmt = $pdo->prepare("SELECT * FROM users"); # prepare query
    $stmt->execute(); # execute
} catch(PDOException $e) { # catch PDO exception
    echo "Error: " . $e->getMessage(); # display message
}