dbconnection.php (1423B)
1 <?php 2 // Singleton class for PDO connection 3 class dbconnection { 4 private static $instance = null; 5 private $pdo; 6 7 private function __construct($host, $dbname, $username, $password) { 8 try { 9 $this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); 10 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 11 } catch (PDOException $e) { 12 if ($e->getCode() == 1045) { 13 logg("User credentials incorrect."); 14 throw $e; 15 } 16 logg($e->getMessage()); 17 } 18 } 19 20 public static function getInstance($host = null, $dbname = null, $username = null, $password = null) { 21 if (self::$instance === null) { 22 if ($host === null || $dbname === null || $username === null || $password === null) { 23 throw new Exception("Database connection parameters are required for the first call to getInstance."); 24 } 25 self::$instance = new dbconnection($host, $dbname, $username, $password); 26 } 27 return self::$instance; 28 } 29 30 public function getPdo() { 31 return $this->pdo; 32 } 33 34 public function getDbName() { 35 return $this->pdo->query('SELECT DATABASE()')->fetchColumn(); 36 } 37 } 38 ?>