• My PHP Pages

    This is a complete and free PHP programming course for beginners. Everything you need to get started is set out in section one below.

Jul 9, 2013

Posted by Unknown
No comments | 5:16 AM

PDO can use exceptions and handle errors. Every time when you use PDO it is good to use it with in try catch block. there is three error modes available in PDO and you can set the error mode attribute on your database.

Lets look at the code.



$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );  
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );  
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); 


No matter what exception mode you set up it will always return an exception value and it must be inside try catch blocks.

Lets see error modes one by one.


PDO::ERRMODE_SILENT

This is the default error mode. If you leave it in this mode, you’ll have to check for errors in the way you’re probably used to if you used the mysql or mysqli extensions. The other two methods are more ideal for DRY programming.

PDO::ERRMODE_WARNING

This mode will issue a standard PHP warning, and allow the program to continue execution. It’s useful for debugging.

PDO::ERRMODE_EXCEPTION

This is the mode you should want in most situations. It fires an exception, allowing you to handle errors gracefully and hide data that might help someone exploit your system. Here’s an example of taking advantage of exceptions:


setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
  
  // Note : Typed DELECT instead of SELECT syntax  
  $DBH->prepare('DELECT name FROM people');  
}  
catch(PDOException $e) {  
    echo "Error Occurred : ".$e->getMessage();  
}  

0 comments :

Post a Comment