Advertisement
Guest User

Untitled

a guest
Jan 15th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.82 KB | None | 0 0
  1. class SQL
  2. {
  3.     private $_connection;
  4.  
  5.     public function __construct( $database = 'default-database', $hostname = 'default-hostname' )
  6.     {
  7.         $this->hostname = $hostname;
  8.         $this->username = 'default-user';
  9.         $this->password = 'default-password';
  10.         $this->database = $database;
  11.  
  12.         $this->_connection = new \mysqli
  13.         (
  14.             $this->hostname,
  15.             $this->username,
  16.             $this->password,
  17.             $this->database
  18.         );
  19.     }
  20.  
  21.     public function __destruct()
  22.     {
  23.         mysqli_close( $this->_connection );
  24.     }
  25.  
  26.     public function execute( $query )
  27.     {
  28.         return $this->getConnection()->query( $query );
  29.     }
  30.  
  31.     private function getConnection()
  32.     {
  33.         if ( !$this->_connection )
  34.             die( 'Connection not initialized, aborting..' );
  35.  
  36.         return $this->_connection;
  37.     }
  38. }
  39.  
  40. // -----------
  41.  
  42. $sql = new SQL( 'different-database' );
  43.  
  44. OR
  45.  
  46. $sql = new SQL( 'different-database', 'different-hostname' );
  47.  
  48. but downside is that you can't only change hostname without providing database, or you have to write this in constructor:
  49.  
  50.    public function __construct( $database = null, $hostname = null )
  51.    {
  52.         $this->hostname = 'default-hostname';
  53.        $this->username = 'default-user';
  54.         $this->password = 'default-password';
  55.        $this->database = 'default-database';
  56.  
  57.        if( $database !== null )
  58.             $this->password = $database;
  59.  
  60.        if( $hostname !== null )
  61.             $this->hostname = $hostname;
  62.  
  63.        $this->_connection = new \mysqli
  64.        (
  65.            $this->hostname,
  66.            $this->username,
  67.            $this->password,
  68.            $this->database
  69.        );
  70.    }
  71.  
  72. but then you still have to write:
  73.  
  74. $sql = new SQL( null, 'hostname' );
  75.  
  76. which is bad
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement