Skip to content

Instantly share code, notes, and snippets.

@mlomb
Last active March 20, 2017 03:17
Show Gist options
  • Save mlomb/a4dd78d5597b9d536e567bfd1be60f59 to your computer and use it in GitHub Desktop.
Save mlomb/a4dd78d5597b9d536e567bfd1be60f59 to your computer and use it in GitHub Desktop.
DB class for PHP
<?php
/*
* No database selected
* Usage:
$query = "SELECT 'testrow' FROM 'database_name'.'table'";
$result = DB::getInstance()->query($query);
if($result->count() != 0){
foreach($result->results() as $row){
$testrow = $row->testrow;
}
}
* Util:
DB::getInstance()->lastInsertId()
*/
class DB{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_lastid,
$_count = 0;
private function __construct(){
try {
global $mysql;
$this->_pdo = new PDO('mysql:host=' . $mysql['host'], $mysql['username'], $mysql['password']);
} catch(PDOException $e){
//die($e->getMessage()); // Enable in case of error
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastid = $this->_pdo->lastInsertId();
} else {
$this->_error = true;
}
//print_r($this->_query->errorInfo()); // Enable in case of error
}
return $this;
}
public function results(){
return $this->_results;
}
public function lastInsertId(){
return $this->_lastid;
}
public function error(){
return $this->_error;
}
public function count(){
return $this->_count;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment