Simple MySQL wrapper around PDO


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

A simple wrapper class for MySql around PDO. Also an example on how to use this wrapper for SQLite.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. // ------------------------------------------------------------------
  4. // - Database class'es -
  5. // ------------------------------------------------------------------
  6.  
  7. /**
  8. * Main database class
  9. * Works as a layer over PDO. Every static call is forwarded to the PDO object, except for those which are defined
  10. *
  11. **/
  12.  
  13. class DB
  14. {
  15. protected static $DB;
  16.  
  17. private function __construct() {}
  18. private function __clone() {}
  19.  
  20. public static function connect($dbname='default', $host='localhost', $user='root', $password='')
  21. {
  22. try {
  23. // connects to the database
  24. self::$DB = new PDO("mysql:dbname=$dbname;host:=$host" , $user , $password);
  25.  
  26. // set the error reporting attribute
  27. self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  28. }
  29. catch(PDOException $e) {
  30. echo $e->getMessage();
  31. }
  32. }
  33.  
  34. public static function close_connection()
  35. {
  36. self::$DB = NULL;
  37. }
  38.  
  39. public static function __callStatic($name, $arguments)
  40. {
  41. return forward_static_call_array(array(self::$DB, $name), $arguments);
  42. }
  43. }
  44.  
  45.  
  46. /**
  47. * A test class
  48. * Using SQLite with 'sqlite::memory:' so that its no need for username, password, etc
  49. * Perfect for quick testing purpose
  50. *
  51. **/
  52.  
  53. class DBtest extends DB
  54. {
  55. public static function connect()
  56. {
  57. try {
  58. self::$DB = new PDO("sqlite::memory:"); // connect to database
  59. echo 'database created in memory <br /> <br />'; // only at debug mode - @TODO: remove it
  60. self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error reporting attribute
  61. }
  62. catch(PDOException $e) {
  63. echo $e->getMessage();
  64. }
  65. }
  66. }
  67.  
  68. // ------------------------------------------------------------------
  69. // - Initilize a standard connection -
  70. // ------------------------------------------------------------------
  71.  
  72.  
  73. include 'config.php';
  74.  
  75. $dbh::connect( $config['db']['default']['dbname'],
  76. $config['db']['default']['host'],
  77. $config['db']['default']['username'],
  78. $config['db']['default']['password']
  79. );
  80.  
  81.  
  82. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.