Skip to content

Instantly share code, notes, and snippets.

@rodrigoespinozadev
Forked from jameskropp/class.database.php
Created August 21, 2018 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigoespinozadev/889657307d4c76e20fa3dd703e183d30 to your computer and use it in GitHub Desktop.
Save rodrigoespinozadev/889657307d4c76e20fa3dd703e183d30 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.
<?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