Thursday, August 8, 2013

Php create a singletone mysql database connection class

<?php

class Database {

    private static $db;
    private $connection;

    private function __construct() {
        $this->connection = new MySQLi("localhost", "my_user", "my_password", "my_db", "3306");
    }

    function __destruct() {
        $this->connection->close();
    }

    public static function getConnection() {
        if ($db == null) {
            $db = new Database();
        }
        return $db->connection;
    }
}

?>
Then just use $db = Database::getConnection(); wherever I need it.

No comments:

Post a Comment