Advertisement
Guest User

DBConnection PHP class

a guest
Aug 2nd, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.24 KB | None | 0 0
  1. <?php
  2.  
  3. class DBConnection {
  4.     protected $username = '';
  5.     protected $password = '';
  6.     protected $dbName = '';
  7.     protected $hostName = '';
  8.  
  9.     function __construct($username, $password, $dbName, $hostname) {
  10.         $this->username = $username;
  11.         $this->password = $password;
  12.         $this->dbName = $dbName;
  13.         $this->hostName = $hostname;
  14.     }
  15.  
  16.     public function getUsername() {
  17.         return $this->username;
  18.     }
  19.  
  20.     public function getPassword() {
  21.         return $this->password;
  22.     }
  23.  
  24.     public function getDbName() {
  25.         return $this->dbName;
  26.     }
  27.  
  28.     public function getHostName() {
  29.         return $this->hostName;
  30.     }
  31.  
  32.     /**
  33.      * Create a PDO connection.
  34.      * @return PDO
  35.      */
  36.     public function connect() {
  37.         try {
  38.             $dbh = new PDO('mysql:host=' . $this->hostName . ';dbname=' . $this->dbName, $this->username, $this->password);
  39.             return $dbh;
  40.         }
  41.         catch (PDOException $e) {
  42.             error_log('Error Could not connect to database. PDOException: ' . $e->getMessage());
  43.             return false;
  44.         }
  45.     }
  46. }
  47.  
  48. $dbh = (new DBConnection('appname', 'lhlftlvevlergjidjbgvtdkdlhrfd', 'appname', 'localhost'))->connect();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement