A friend of mine (on twitter) sent to me a small piece of code to interface a MySQL database using PHP and Object Oriented Programming

I'm very happy to post it.

Here you are the code:

 

  1. <?php
  2.  
  3. class DB {
  4.     const NAME     = 'yourdbname';
  5.     const USER     = 'yourdbuser';
  6.     const PASSWORD = 'yourdbpassword';
  7.     const HOST     = 'yourdbhost';
  8. }
  9.  
  10. $conn = mysql_connect(DB::HOST, DB::USER, DB::PASSWORD);
  11. mysql_select_db(DB::NAME, $conn);
  12.  
  13. if ( !$conn ) {
  14.     die('Could not connect ' . mysql_error());
  15. }
  16.  
  17. ?>
  18.  
  19. or better yet
  20.  
  21. <?php
  22.  
  23. class DB {
  24.     const NAME     = 'yourdbname';
  25.     const USER     = 'yourdbuser';
  26.     const PASSWORD = 'yourdbpassword';
  27.     const HOST     = 'yourdbhost';
  28.    
  29.     private $connection;
  30.     //more properties here
  31.  
  32.     public function __construct() {
  33.         $this->conn = mysql_connect(self::HOST, self::USER, self::PASSWORD);
  34.         mysql_select_db(self::NAME, $this->connection);
  35.  
  36.         if ( !$this->connection ) {
  37.             throw new Exception(mysql_error());
  38.         }
  39.     }
  40.  
  41.     //methods here
  42. }
  43.  
  44. try {
  45.     $db = new DB();
  46.     //method calls here
  47. } catch (Exception $e) {
  48.     echo 'Could not connect ' . $e->getMessage;
  49. }
  50.  
  51. ?>
  52.  
  53. Notes:
  54. – Constants are static members.
  55. – Constants cannot be private. This design constraint is due to reflection.

 

The author is @desiradaniel