php - pdo singleton connection class

php
voted: 0
vote
php mysql pdo singleton connection

Php connection class returning instance. Using singleton pattern.

//database.php
<?php

require_once 'dbconfig.php';
class Database {

     private static $_instance;

     public function &pdoConnection(){
        if(!self::$_instance){
            try {
                self::$_instance = new PDO(DSN,USERNAME,PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
                self::$_instance->setAttribute(PDO::ATTR_PERSISTENT, true);
                self::$_instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
            catch(PDOException $e) {
                die("pdo connection error! ". $e->getMessage() ."<br/>");
            }
        }
        return self::$_instance;
    }
    private function  __construct() {
    }
    private function __clone() {}
}
?>

//dbconfig.php
<?php
define('USERNAME','root');
define('PASSWORD','1234');
define('DSN',"mysql:host=localhost;dbname=database");
?>
working url: not entered
version: not entered
Leave a Comment:
Characters left:
No comments yet.