Mustafa Ekici Mustafa Ekici - 8 months ago 29
MySQL Question

What is the best way to use try and catch in PDO

I think the code below is the best way to use try and catch in php using PDO.

In the catch I describe the: line number, file and errormessage



// code that works


catch(PDOException $e)
$errormessage = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'


If someone knows a better way to write a try and catch, please write it below.


Here is a simple example of a Class that extends PDO that might give you some ideas:


    defined("HOST")         or define("HOST",           "localhost");
    defined("DBASE")        or define("DBASE",          "dbName");
    defined("USER")         or define("USER",           "root");
    defined("PASS")         or define("PASS",           "root");

    class DB extends PDO {

         * @var PDO
        private static $dbHandle;

        public static function getInstance(){
            try {
                self::$dbHandle = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
                self::$dbHandle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                return self::$dbHandle;
            }catch(PDOException $e){
                throw new Exception($e->getMessage());

        public static function getHandle(){
                self::$dbHandle = self::getInstance();
            return self::$dbHandle;