Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. <?php
  2. class Db
  3. {
  4. private $_connection;
  5. private static $_instance; //The single instance
  6. private $_host = DB_HOST;
  7. private $_username = DB_USER;
  8. private $_password = DB_PASSWORD;
  9. private $_database = DB_DB;
  10.  
  11. /*
  12. Get an instance of the Database
  13. @return Instance
  14. */
  15. public static function getInstance()
  16. {
  17. if (!self::$_instance) { // If no instance then make one
  18. self::$_instance = new self();
  19. }
  20. return self::$_instance;
  21. }
  22.  
  23. // Constructor
  24. private function __construct()
  25. {
  26. try {
  27.  
  28. $this->_connection = new \PDO("mysql:host=$this->_host;dbname=$this->_database", $this->_username, $this->_password);
  29. /*** echo a message saying we have connected ***/
  30. echo 'Connected to database';
  31. } catch (PDOException $e) {
  32. echo $e->getMessage();
  33. }
  34. }
  35.  
  36. // Magic method clone is empty to prevent duplication of connection
  37. private function __clone()
  38. {
  39. }
  40.  
  41. // Get mysql pdo connection
  42. public function getConnection()
  43. {
  44. return $this->_connection;
  45. }
  46. }
  47.  
  48. /**
  49. * And you can use it as such in a class
  50. * */
  51.  
  52. class Post {
  53.  
  54. public function __construct(){
  55. $db = Db::getInstance();
  56. $this->_dbh = $db->getConnection();
  57.  
  58. }
  59.  
  60. public function getPosts()
  61. {
  62. try {
  63.  
  64. /*** The SQL SELECT statement ***/
  65. $sql = "SELECT * FROM posts";
  66. foreach ($this->_dbh->query($sql) as $row) {
  67. var_dump($row);
  68. }
  69.  
  70. /*** close the database connection ***/
  71. $this->_dbh = null;
  72. } catch (PDOException $e) {
  73. echo $e->getMessage();
  74. }
  75. }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement