PDO has 3 types error handling strategies,in php application development.
- PDO::ERRMODE_SILENT PDO will simply set the error code by default to inspect using the PDO::errorCode() and PDO::errorInfo() on both database objects and statements; if the error resulted from a call on a statement object, you should use the PDOStatement::errorCode() or PDOStatement::errorInfo( method on that object. If the error resulted from a call on the database object, we should use those methods on the database object.
- PDO::ERRMODE_WARNING PDO will show a traditional WARNING message if we use ERRMODE_WARNING . This setting is useful while debugging/testing the code, if we want to see what problems occurred without disturbing the application.This will show errorcode also in warning.
- PDO::ERRMODE_EXCEPTION PDO will throw a PDO Exception and set its properties to reflect the error code and error information. This setting is while debugging the code, as it will effectively point to the error very quickly in the code (Transactions are automatically roll back if the exception occurs).
- Exception mode is also usefult o structure error
handling clearly than with normal PHP warnings and errors.
PDO Hanling Exception Example
<?php $host = 'mysql:dbname=testdb;host=localhost'; $username = 'root'; $password = ''; //try catch block for handling pdo exception try { $pdoObj = new PDO($host, $username, $password); $pdoObj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $ex) { echo 'Connection failed: ' . $ex->getMessage(); } //The example shown above is handling the exception //if the connection using pdo is failed then it will //echo connection faild adn the errormessage which is generated by PDOException class ?>
No comments:
Post a Comment