Latest web development tutorials

PHP PDO error with error handling

PHP PDO Reference Manual PHP PDO Reference Manual

  • PDO :: ERRMODE_SILENT

    This is the default mode. PDO will simply set the error code, use the PDO :: errorCode () and PDO :: errorInfo () method to check the statement and database objects. If the error is due to the object of the call statement is generated, then you can call that object PDOStatement :: errorCode () or PDOStatement :: errorInfo () method. If the error resulted from a call on the database object, then invoke those methods on the database object.

  • PDO :: ERRMODE_WARNING

    In addition to setting the error code addition, PDO will emit a traditional E_WARNING message. If you just want to see what problems occurred without interrupting the flow of the application, so this setting in debugging / testing period is very useful.

  • PDO :: ERRMODE_EXCEPTION

    In addition to setting the error code addition, PDO will throw an exception PDOException class and set its properties to reflect the error code and error messages. This setting is also useful during debugging, because a wrong point it will effectively enlarge the script, which can very quickly point out potential problem area code (remember: if the exception causes the script to terminate the transaction is automatically back roll).

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

Create a PDO instance and set 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 the current set PDO :: ATTR_ERRMODE, if the connection fails, PDO :: __ construct () will always throw a PDOException exception. Uncaught exception is fatal.

Create a PDO instance and set 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 Reference Manual PHP PDO Reference Manual