Skip to content

Instantly share code, notes, and snippets.

@vishnukumarpv
Forked from jonashansen229/class.database.php
Last active August 29, 2016 09:56
Show Gist options
  • Save vishnukumarpv/7e9efd015b0cf812be59b91c3415d00e to your computer and use it in GitHub Desktop.
Save vishnukumarpv/7e9efd015b0cf812be59b91c3415d00e 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.
<?php
/*
* Mysql database class - only one connection alowed
*/
class Database {
private $_connection;
private static $_instance; //The single instance
private $_host = "HOSTt";
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: " . mysql_connect_error(),
E_USER_ERROR);
}
}
// Magic method clone is empty to prevent duplication of connection
private function __clone() { }
// Get mysqli connection
public function getConnection() {
return $this->_connection;
}
}
?>
<?php
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql_query = "SELECT foo FROM .....";
$result = $mysqli->query($sql_query);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment