-
-
Save jameskropp/eb2b2cc9668a65da0aabc105f8140374 to your computer and use it in GitHub Desktop.
PHP OOP Database class using PDO and Singleton pattern. Only one instance of the class will be made, this requires less memory.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Mysql database class - only one connection alowed | |
*/ | |
<?php | |
class DB { | |
private $connection; | |
private static $_instance; | |
private $dbhost = "localhost"; // Ip Address of database if external connection. | |
private $dbuser = "root"; // Username for DB | |
private $dbpass = "root"; // Password for DB | |
private $dbname = "root"; // DB Name | |
/* | |
Get an instance of the Database | |
@return Instance | |
*/ | |
public static function getInstance(){ | |
if(!self::$_instance) { | |
self::$_instance = new self(); | |
} | |
return self::$_instance; | |
} | |
// Constructor | |
private function __construct() { | |
try{ | |
$this->connection = new PDO('mysql:host='.$this->dbhost.';dbname='.$this->dbname, $this->dbuser, $this->dbpass); | |
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
// Error handling | |
}catch(PDOException $e){ | |
die("Failed to connect to DB: ". $e->getMessage()); | |
} | |
} | |
// Magic method clone is empty to prevent duplication of connection | |
private function __clone(){} | |
// Get the connection | |
public function getConnection(){ | |
return $this->connection; | |
} | |
} | |
$db = DB::getInstance(); | |
$conn = $db->getConnection(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi James, my question is, what if I need to pass the dbname by parameter? How would I do it?