Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. <?php
  2.  
  3. namespace model;
  4.  
  5. use PDO;
  6.  
  7. /*
  8. * PDO Database Class
  9. * Connect to database
  10. * Create prepared statements
  11. * Bind Values
  12. * Return rows and results
  13. */
  14.  
  15. include './config/config.php';
  16.  
  17. class Database
  18. {
  19. private $host = DB_HOST;
  20. private $user = DB_USER;
  21. private $pass = DB_PASS;
  22. private $databaseName = DB_NAME;
  23.  
  24. private $databaseHandler;
  25. private $statement;
  26. private $error;
  27. private $dsn;
  28.  
  29.  
  30. public function __construct()
  31. {
  32. // set DSN
  33. $this->dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->databaseName;
  34. // TODO : check for more usefull options
  35. $options = array(
  36. PDO::ATTR_PERSISTENT => true, // Persistent connection -increase preformance
  37. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Handle errors
  38. );
  39.  
  40. $this->createNewPDO();
  41. }
  42.  
  43. private function createNewPDO()
  44. {
  45. try {
  46. $this->databaseHandler = new PDO($this->dsn, $this->user, $this->pass);
  47. } catch (PDOExeption $error) {
  48. $this->error = $error->getMessage();
  49. echo $this->error;
  50. }
  51. }
  52.  
  53. // Prepare statement with query
  54. public function query($sql)
  55. {
  56. $this->statement = $this->databaseHandler->prepare($sql);
  57. }
  58.  
  59. // Bind values & check which type is passed in
  60. public function bind($param, $value, $type = null)
  61. {
  62. if (is_null($type)) {
  63. switch (true) {
  64. case is_int($value):
  65. $type = PDO::PARAM_INT;
  66. break;
  67. case is_bool($value):
  68. $type = PDO::PARAM_BOOL;
  69. break;
  70. case is_null($value):
  71. $type = PDO::PARAM_NULL;
  72. break;
  73. default:
  74. $type = PDO::PARAM_STR;
  75. }
  76. }
  77. $this->statement->bindValue($param, $value, $type);
  78. }
  79.  
  80. // Execute the prepared statment
  81. public function execute()
  82. {
  83. return $this->statement->execute();
  84. }
  85.  
  86. // Get single record as object
  87. public function single()
  88. {
  89. $this->execute();
  90. return $this->statement->fetch(PDO::FETCH_OBJ);
  91. }
  92.  
  93. // Get row count
  94. public function rowCount()
  95. {
  96. return $this->statement->rowCount();
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement