stack
stack

Reputation: 10228

Writing a database connection in index.php file

I have a PDO connection to database in index.php file.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$dbh_conn->exec("set names utf8");
$dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Almost all pages of my website need database. Also there is a few pages which don't need database, but because all pages pass from index.php then that connection executes. I mean for all pages (even those ones which doesn't need database) there is a database connection.

Is that a bad thing? Should I change all my structure? Again, the most of the pages need database, just a few of them doesn't. So is what I do fine?

Upvotes: 1

Views: 1082

Answers (1)

Alon Eitan
Alon Eitan

Reputation: 12025

You need to create a singleton class for the DB connection, and not just run the code.

class DB {
    private static $instance;
    private $_dbh_conn = null;

    public static function getInstance() {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    protected function __construct() { 
        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "dbname";
        $this->_dbh_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $this->_dbh_conn->exec("set names utf8");
        $this->_dbh_conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $this->_dbh_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function &dbh_conn() {
        return $this->_dbh_conn;
    }

    private function __clone() { }
    private function __wakeup() { }
}

And when you include this file, you need to get the connection like this:

$dbh_conn = DB::getInstance()->dbh_conn(); 

Now you have the connection to the database in $dbh_conn and you can use it just as you did up until now. The only difference is that now you can include this file, but it won't connect to the DB unless you use the Singleton class DB and specifically requesting the DB connection (as I did in the above example). Additional benefit is that you're getting the same DB connection throughout the runtime of the script because you're using a design pattern of a singleton class to get the connection.

Upvotes: 1

Related Questions