Mustafa Ekici Mustafa Ekici - 2 months ago 12
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


error_reporting(E_ALL);

try{

// code that works

}

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

trigger_error($errormessage);
}


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

Answer

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

<?php

    //DATABASE CONNECTION CONFIGURATION:
    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(){
            if(!isset(self::$dbHandle)){
                self::$dbHandle = self::getInstance();
            }
            return self::$dbHandle;
        }
    }