PHP PDO Errors and Error Handling

PHP PDO 参考手册PHP PDO Reference Manual

  • PDO::ERRMODE_SILENT

    This is the default mode. PDO will simply set the error code, and you can use the PDO::errorCode() and PDO::errorInfo() methods to check the statement and database objects. If the error is caused by a call to a statement object, you can call that object's PDOStatement::errorCode() or PDOStatement::errorInfo() methods. If the error is caused by a call to a database object, you can call the above two methods on the database object.

  • PDO::ERRMODE_WARNING

    In addition to setting the error code, PDO will also issue a traditional E_WARNING message. If you just want to see what went wrong without interrupting the application's flow, this setting is very useful during debugging/testing.

  • PDO::ERRMODE_EXCEPTION

    In addition to setting the error code, PDO will also throw a PDOException exception class and set its properties to reflect the error code and error message. This setting is also very useful during debugging because it effectively amplifies the point in the script where the error occurs, allowing you to quickly identify potentially problematic areas in the code (remember: if the exception causes the script to terminate, the transaction is automatically rolled back).

    Another very useful aspect of exception mode is that, compared to traditional PHP-style warnings, you can build your own error handling more clearly, and compared to silent mode and explicitly checking the return value of every database call, exception mode requires less code/nesting.

Create a PDO instance and set the error mode

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

?>

Note:Regardless of whether PDO::ATTR_ERRMODE is currently set, if the connection fails, PDO::__construct() will always throw a PDOException. An uncaught exception is fatal.

Create a PDO instance and set the error mode in the constructor

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';

/*
    使用 try/catch 围绕构造函数仍然有效,即使设置了 ERRMODE 为 WARNING,
    因为如果连接失败,PDO::__construct 将总是抛出一个  PDOException 异常。
*/
try {
    $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
    exit;
}

// 这里将导致 PDO 抛出一个 E_WARNING 级别的错误,而不是 一个异常 (当数据表不存在时)
$dbh->query("SELECT wrongcolumn FROM wrongtable");
?>

The above example will output:

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 18
add a note add a note

PHP PDO 参考手册PHP PDO Reference Manual

Other Extensions