Database Connection


/ Published in: PHP
Save to your folder(s)

Allows you to connect to different datasources. Very common to use something like this for development,staging and production deployments.


Copy this code and paste it in your HTML
  1. <?php
  2. /*
  3. |---------------------------
  4. | Author: Evin Weissenberg
  5. |---------------------------
  6. */
  7. class Connection {
  8.  
  9. public static $db = '1'; // 1=production, 2=staging, 3=development.
  10.  
  11. //PRODUCTION
  12. public static $host_1 = '';
  13. public static $username_1 = '';
  14. public static $password_1 = '';
  15. public static $db_name_1 = '';
  16. public static $port_1 = '';
  17.  
  18. //STAGING
  19. public static $host_2 = '';
  20. public static $username_2 = '';
  21. public static $password_2 = '';
  22. public static $db_name_2 = '';
  23. public static $port_2 = '';
  24.  
  25. //DEVELOPMENT
  26. public static $host_3 = 'localhost';
  27. public static $username_3 = 'root';
  28. public static $password_3 = 'password';
  29. public static $db_name_3 = 'my_database';
  30. public static $port_3 = '3306';
  31.  
  32. public static function dbConnection() {
  33.  
  34. if (self::$db == 1) {
  35.  
  36. mysql_connect(self::$host_1, self::$username_1, self::$password_1) or die(mysql_error());
  37. mysql_select_db(self::$db_name_1) or die(mysql_error());
  38.  
  39. return true;
  40.  
  41. } elseif (self::$db == 2) {
  42.  
  43. mysql_connect(self::$host_2, self::$username_2, self::$password_2) or die(mysql_error());
  44. mysql_select_db(self::$db_name_2) or die(mysql_error());
  45.  
  46. return true;
  47.  
  48. } elseif (self::$db == 3) {
  49.  
  50. mysql_connect(self::$host_3, self::$username_3, self::$password_3) or die(mysql_error());
  51. mysql_select_db(self::$db_name_3) or die(mysql_error());
  52.  
  53. return true;
  54.  
  55.  
  56. } else {
  57.  
  58. return false;
  59.  
  60. }
  61. }
  62. }
  63.  
  64. //Usage
  65. Connection::$db=3;
  66. Connection::dbConnection();

URL: http://www.evinw.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.