Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * PDO Database Class
- * Connect to database
- * Creates prepared statements
- * Bind values
- * Returns rows & results
- */
- class Database {
- private $host = DB_HOST;
- private $dbname = DB_NAME;
- private $user = DB_USER;
- private $pass = DB_PASS;
- private $dbh;
- private $stmt;
- private $error;
- public function __construct() {
- // Set DSN
- $dsn = 'mysql:host=' .$this->host. ';dbname=' .$this->dbname;
- // Set PDO options
- $options = array(
- PDO::ATTR_PERSISTENT => true,
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
- );
- // Create PDO instance
- try {
- $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
- }
- catch(PDOException $e) {
- $this->error = $e->getMessage();
- echo $this->error;
- }
- }
- // Prepare statement with query
- public function query($sql) {
- $this->stmt = $this->dbh->prepare($sql);
- }
- // Bind values
- public function bind($param, $value, $type = null) {
- // Check type and associate with PDO type
- if(is_null(true)) {
- switch($type) {
- case is_int($value):
- $type = PDO::PARAM_INT;
- break;
- case is_bool($value):
- $type = PDO::PARAM_BOOL;
- break;
- case is_null($value):
- $type = PDO::PARAM_NULL;
- break;
- default:
- $type = PDO::PARAM_STRING;
- }
- }
- $this->stmt->bindValue($param, $value, $type);
- }
- // Execute prepared statement
- public function execute() {
- return $this->stmt->execute();
- }
- // Get result set as an array of objects
- public function resultSet() {
- $this->execute();
- return $this->stmt->fetchAll(PDO::FETCH_OBJ);
- }
- // Get single record as object
- public function single() {
- $this->execute();
- return $this->stmt->fetch(PDO::FETCH_OBJ);
- }
- // Get row count
- public function rowCount() {
- return $this->stmt->rowCount();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement