Advertisement
Guest User

Untitled

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