Php Pdo Error Handling
# PHP PDO Errors and Error Handling
[PHP PDO Reference](#)
* **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 the statement and database objects. If the error resulted from a call to a statement object, you can call the `PDOStatement::errorCode()` or `PDOStatement::errorInfo()` methods on that object. If the error resulted from a call to the 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. This setting is very useful during debugging/testing if you just want to see what went 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 and set its properties to reflect the error code and error information. This setting is also very useful during debugging, as it effectively highlights the point in the script where an error occurred, making it very easy to pinpoint the potential area of problematic 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 it allows for much cleaner error handling construction compared to traditional PHP-style warnings, and requires less code/nesting than silent mode and explicitly checking the return value of every database call.
### Creating a PDO Instance and Setting the Error Mode
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage();}?>
**Note:** Regardless of the current `PDO::ATTR_ERRMODE` setting, `PDO::__construct()` will always throw a `PDOException` exception if the connection fails. An uncaught exception is fatal.
### Creating a PDO Instance and Setting the Error Mode in the Constructor
PDO::ERRMODE_WARNING));} catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); exit;}// This will cause PDO to throw an E_WARNING level error, not an exception (when the table does not exist) $dbh->query("SELECT wrongcolumn FROM wrongtable");?>
The above example will output:
Warning: PDO::query(): SQLSTATE: 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](#)
YouTip