Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.67 KB | None | 0 0
  1. <?php
  2.  
  3. final class MySQL
  4. {
  5.     private static $instance;
  6.  
  7.     private static $hasInstance = false;
  8.  
  9.     private $db_link;
  10.  
  11.     public $db_count = 0;
  12.  
  13.  
  14.     public static function getInstance()
  15.     {
  16.         if (self::$instance === null) {
  17.             self::$instance = new self();
  18.         }
  19.  
  20.         return self::$instance;
  21.     }
  22.  
  23.     private function __construct()
  24.     {
  25.  
  26.         if (!self::$hasInstance) {
  27.             $this->db_link = new mysqli(BD_HOST, BD_USER, BD_PASS, BD_NAME);
  28.  
  29.             if ($this->db_link->connect_errno) {
  30.                 throw new \Exception($this->db_link->connect_error);
  31.             }
  32.  
  33.             $this->db_link->set_charset("utf8");
  34.         } else {
  35.             throw new \Exception("Class is already instantiated.");
  36.         }
  37.  
  38.         self::$hasInstance = true;
  39.     }
  40.  
  41.     private function __clone()
  42.     {
  43.         throw new \Exception("Class could not be cloned.");
  44.     }
  45.  
  46.     private function __wakeup()
  47.     {
  48.         throw new \Exception("Cannot unserialize a singleton.");
  49.     }
  50.  
  51.     public function query($sql)
  52.     {
  53.         $query = $this->db_link->query($sql);
  54.  
  55.         $this->db_count += 1;
  56.  
  57.         if ($this->db_link->errno) {
  58.             throw new \Exception($this->db_link->error);
  59.         }
  60.  
  61.         return $query;
  62.     }
  63.  
  64.     private function fetch_assoc($result)
  65.     {
  66.         return $result->fetch_assoc();
  67.     }
  68.  
  69.     public function insert_id()
  70.     {
  71.         return $this->db_link->insert_id;
  72.     }
  73.  
  74.     private function num_rows($result)
  75.     {
  76.         return $result->num_rows;
  77.     }
  78.  
  79.     public function __destruct()
  80.     {
  81.         $this->db_link->close();
  82.     }
  83. }
  84.  
  85. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement