-
-
Save gruff1991/07789325966117cedeb71b4f10abef8a to your computer and use it in GitHub Desktop.
PHP OOP Database class using MySQLI and Singleton pattern. Only one instance of the class will be made, this requires less memory.
This file contains 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 | |
*/ | |
class Database { | |
private $_connection; | |
private static $_instance; //The single instance | |
private $_host = "HOST"; | |
private $_username = "USERNAME"; | |
private $_password = "PASSWORD"; | |
private $_database = "DATABASE"; | |
/* | |
Get an instance of the Database | |
@return Instance | |
*/ | |
public static function getInstance() { | |
if(!self::$_instance) { // If no instance then make one | |
self::$_instance = new self(); | |
} | |
return self::$_instance; | |
} | |
// Constructor | |
private function __construct() { | |
$this->_connection = new mysqli($this->_host, $this->_username, | |
$this->_password, $this->_database); | |
// Error handling | |
if(mysqli_connect_error()) { | |
trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error()); | |
} | |
} | |
// Magic method clone is empty to prevent duplication of connection | |
private function __clone() { } | |
// Get mysqli connection | |
public function getConnection() { | |
return $this->_connection; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The E_USER_ERROR was causing a parsing error for myself, so removed it, also the mysql_connect_error is depreciated so updated it to mysqli_connect_error.