Advertisement
Guest User

Untitled

a guest
Apr 5th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. class BetterPDO extends PDO
  2. {
  3. private $realPDO = NULL;
  4. private $dsn = "";
  5. private $username = "";
  6. private $password = "";
  7. private $options = [];
  8.  
  9. public function __construct ($dsn, $username = "", $password = "", $options = [])
  10. {
  11. $this -> dsn = $dsn;
  12. $this -> username = $username;
  13. $this -> password = $password;
  14. $this -> options = $options;
  15. }
  16.  
  17. private function getRealPDO ()
  18. {
  19. if (is_null ($this -> realPDO))
  20. {
  21. $this -> realPDO = new PDO ($this -> dsn, $this -> username, $this -> password, $this -> options);
  22. }
  23. return $this -> realPDO;
  24. }
  25.  
  26. // We're only implementing exec for brevity but you have to do this for all public methods of PDO
  27. public function exec ($sql)
  28. {
  29. $retries = 0;
  30. while (true)
  31. {
  32. try
  33. {
  34. return $this -> getRealPDO () -> exec ($sql);
  35. }
  36. catch (PDOException $ex)
  37. {
  38. $this -> realPDO = NULL;
  39. if (++$retries > 5)
  40. {
  41. // We've passed our retry limit
  42. throw $ex;
  43. }
  44. }
  45. }
  46. }
  47. }
  48.  
  49. /* Your Database Name */
  50. $dbname = 'mydatabase';
  51.  
  52. /* Your Database User Name and Passowrd */
  53. $username = 'root';
  54. $password = 'password';
  55.  
  56. try {
  57. /* Establish the database connection */
  58. $conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
  59. $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  60. /* your code goes here*/
  61. } catch(PDOException $e) {
  62. echo 'ERROR: ' . $e->getMessage();
  63. }
  64. //mysql_close($conn);
  65.  
  66. $conn=null;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement