Mustafa Ekici Mustafa Ekici - 1 year ago 51
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.

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download