Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. <?php
  2. /*
  3. * Mysql database class - only one connection alowed
  4. */
  5. <?php
  6.  
  7. class DB {
  8. private $connection;
  9. private static $_instance;
  10.  
  11. private $dbhost = "localhost"; // Ip Address of database if external connection.
  12. private $dbuser = "root"; // Username for DB
  13. private $dbpass = "root"; // Password for DB
  14. private $dbname = "root"; // DB Name
  15.  
  16. /*
  17. Get an instance of the Database
  18. @return Instance
  19. */
  20. public static function getInstance(){
  21. if(!self::$_instance) {
  22. self::$_instance = new self();
  23. }
  24. return self::$_instance;
  25. }
  26.  
  27. // Constructor
  28. private function __construct() {
  29. try{
  30. $this->connection = new PDO('mysql:host='.$this->dbhost.';dbname='.$this->dbname, $this->dbuser, $this->dbpass);
  31. $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  32.  
  33. // Error handling
  34. }catch(PDOException $e){
  35. die("Failed to connect to DB: ". $e->getMessage());
  36. }
  37. }
  38.  
  39. // Magic method clone is empty to prevent duplication of connection
  40. private function __clone(){}
  41.  
  42. // Get the connection
  43. public function getConnection(){
  44. return $this->connection;
  45. }
  46. }
  47.  
  48. $db = DB::getInstance();
  49. $conn = $db->getConnection();
  50.  
  51. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement