Guest User

Untitled

a guest
May 7th, 2019
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. <?php
  2. /*
  3. * PDO DATABASE CLASS
  4. * Connects Database Using PDO
  5. * Creates Prepeared Statements
  6. * Binds params to values
  7. * Returns rows and results
  8. */
  9. class Database {
  10. private $host = DB_HOST;
  11. private $user = DB_USER;
  12. private $pass = DB_PASS;
  13. private $dbname = DB_NAME;
  14.  
  15. private $dbh;
  16. private $error;
  17. private $stmt;
  18.  
  19. public function __construct() {
  20. // Set DSN
  21. $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
  22. $options = array (
  23. PDO::ATTR_PERSISTENT => true,
  24. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  25. );
  26.  
  27. // Create a new PDO instanace
  28. try {
  29. $this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
  30. } // Catch any errors
  31. catch ( PDOException $e ) {
  32. $this->error = $e->getMessage();
  33. }
  34. }
  35.  
  36. // Prepare statement with query
  37. public function query($query) {
  38. $this->stmt = $this->dbh->prepare($query);
  39. }
  40.  
  41. // Bind values
  42. public function bind($param, $value, $type = null) {
  43. if (is_null ($type)) {
  44. switch (true) {
  45. case is_int ($value) :
  46. $type = PDO::PARAM_INT;
  47. break;
  48. case is_bool ($value) :
  49. $type = PDO::PARAM_BOOL;
  50. break;
  51. case is_null ($value) :
  52. $type = PDO::PARAM_NULL;
  53. break;
  54. default :
  55. $type = PDO::PARAM_STR;
  56. }
  57. }
  58. $this->stmt->bindValue($param, $value, $type);
  59. }
  60.  
  61. // Execute the prepared statement
  62. public function execute(){
  63. return $this->stmt->execute();
  64. }
  65.  
  66. // Get result set as array of objects
  67. public function resultset(){
  68. $this->execute();
  69. return $this->stmt->fetchAll(PDO::FETCH_OBJ);
  70. }
  71.  
  72. // Get single record as object
  73. public function single(){
  74. $this->execute();
  75. return $this->stmt->fetch(PDO::FETCH_OBJ);
  76. }
  77.  
  78. // Get record row count
  79. public function rowCount(){
  80. return $this->stmt->rowCount();
  81. }
  82.  
  83. // Returns the last inserted ID
  84. public function lastInsertId(){
  85. return $this->dbh->lastInsertId();
  86. }
  87. }
Add Comment
Please, Sign In to add comment