PDO::ERRMODE_SILENT
This is the default mode. PDO will simply set the error code, which can be checked using the PDO::errorCode() and PDO::errorInfo() methods on statements and database objects. If the error occurs due to a call to a statement object, you can call that object's PDOStatement::errorCode() or PDOStatement::errorInfo() method. If the error is caused by calling a database object, then the above two methods can be called on the database object.
PDO::ERRMODE_WARNING
In addition to setting the error code, PDO will also send a traditional E_WARNING message. This setting is useful during debugging/testing if you just want to see what's going wrong without interrupting the flow of your application.
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 information. This setting is also very useful during debugging, as it effectively zooms in on the point in the script where the error occurred, allowing you to very quickly pinpoint potential problematic areas in the code (remember: if an exception causes the script to terminate, the transaction is automatically rolled back roll).
Another very useful thing about exception mode is that you can build your own error handling more clearly than traditional PHP-style warnings, and it requires less code than silent mode and explicitly checking the return value of each database call. /Less nested.
<?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, PDO::__construct() will always throw a PDOException if the connection fails. Uncaught exceptions are fatal.
<?php$dsn = 'mysql:dbname=test;host=127.0.0.1';$user = 'googleguy';$password = 'googleguy';/* Using try/catch around the constructor still works even if ERRMODE is set WARNING because PDO::__construct will always throw a PDOException if the connection fails. */try { $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));} catch (PDOException $e) { echo 'Connection failed: ' . $ e->getMessage(); exit;}//This will cause PDO to throw an E_WARNING level error, rather than an exception (when the data table does not exist) $dbh->query("SELECT wrongcolumn FROM wrongtable");?>
The above routine 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 18add a note add a note