Advertisement
Guest User

Untitled

a guest
May 9th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 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 $port = DB_PORT; //Add option for optional Port for the SQL Engine
  12. private $user = DB_USER;
  13. private $pass = DB_PASS;
  14. private $dbname = DB_NAME;
  15.  
  16. private $dbh;
  17. private $error;
  18. private $stmt;
  19.  
  20. public function __construct() {
  21. if ( defined('DB_PORT')) {
  22. // Set DSN, with the provided Port
  23. $dsn = 'mysql:host=' . $this->host. ':' . $this->port . ';dbname=' . $this->dbname;
  24. } else {
  25. // Set DSN - default port for MySQL Server which is 3306
  26. $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
  27. }
  28. $options = array (
  29. PDO::ATTR_PERSISTENT => true,
  30. PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  31. );
  32.  
  33. // Create a new PDO instanace
  34. try {
  35. $this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
  36. } // Catch any errors
  37. catch ( PDOException $e ) {
  38. $this->error = $e->getMessage();
  39. }
  40. }
  41.  
  42. // Prepare statement with query
  43. public function query($query) {
  44. $this->stmt = $this->dbh->prepare($query);
  45. }
  46.  
  47. // Bind values
  48. public function bind($param, $value, $type = null) {
  49. if (is_null ($type)) {
  50. switch (true) {
  51. case is_int ($value) :
  52. $type = PDO::PARAM_INT;
  53. break;
  54. case is_bool ($value) :
  55. $type = PDO::PARAM_BOOL;
  56. break;
  57. case is_null ($value) :
  58. $type = PDO::PARAM_NULL;
  59. break;
  60. default :
  61. $type = PDO::PARAM_STR;
  62. }
  63. }
  64. $this->stmt->bindValue($param, $value, $type);
  65. }
  66.  
  67. // Execute the prepared statement
  68. public function execute(){
  69. return $this->stmt->execute();
  70. }
  71.  
  72. // Get result set as array of objects
  73. public function resultset(){
  74. $this->execute();
  75. return $this->stmt->fetchAll(PDO::FETCH_OBJ);
  76. }
  77.  
  78. // Get single record as object
  79. public function single(){
  80. $this->execute();
  81. return $this->stmt->fetch(PDO::FETCH_OBJ);
  82. }
  83.  
  84. // Get record row count
  85. public function rowCount(){
  86. return $this->stmt->rowCount();
  87. }
  88.  
  89. // Returns the last inserted ID
  90. public function lastInsertId(){
  91. return $this->dbh->lastInsertId();
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement