Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.23 KB | None | 0 0
  1. <?php
  2. /*
  3. * Mysql database class - only one connection alowed
  4. */
  5. class DB {
  6.     private $_connection;
  7.     private static $_instance; //The single instance
  8.     private $_host = "HOSTt";
  9.     private $_username = "USERNAME";
  10.     private $_password = "PASSWORd";
  11.     private $_database = "DATABASE";
  12.  
  13.     /*
  14.     Get an instance of the Database
  15.     @return Instance
  16.     */
  17.     public static function getInstance() {
  18.         if(!self::$_instance) { // If no instance then make one
  19.             self::$_instance = new self();
  20.         }
  21.         return self::$_instance;
  22.     }
  23.  
  24.     // Constructor
  25.     private function __construct() {
  26.         $this->_connection = new mysqli($this->_host, $this->_username,
  27.             $this->_password, $this->_database);
  28.    
  29.         // Error handling
  30.         if(mysqli_connect_error()) {
  31.             trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
  32.                  E_USER_ERROR);
  33.         }
  34.     }
  35.  
  36.     // Magic method clone is empty to prevent duplication of connection
  37.     private function __clone() { }
  38.  
  39.     // Get mysqli connection
  40.     public function getConnection() {
  41.         return $this->_connection;
  42.     }
  43. }
  44. ?>
  45.  
  46.  
  47. //*********************************
  48. EXEMPLO de USO
  49.  $db = DB::getInstance();
  50.  $mysqli = $db->getConnection();
  51.  $sql_query = "SELECT foo FROM .....";
  52.  $result = $mysqli->query($sql_query);
  53. **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement