Skip to content

Instantly share code, notes, and snippets.

@jameskropp
Forked from jonashansen229/class.database.php
Last active November 26, 2022 20:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jameskropp/eb2b2cc9668a65da0aabc105f8140374 to your computer and use it in GitHub Desktop.
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.
<?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();
?>
@NotesAmade
Copy link

Hi James, my question is, what if I need to pass the dbname by parameter? How would I do it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment