Skip to content

Instantly share code, notes, and snippets.

@jmmaguigad
Last active February 2, 2020 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmmaguigad/40888a43819ea5e843443c24b9ac7aea to your computer and use it in GitHub Desktop.
Save jmmaguigad/40888a43819ea5e843443c24b9ac7aea to your computer and use it in GitHub Desktop.
DB Query Builder Class
<?php
/*
* DB Query Builder Class
* References:
* Curtis Parham => https://www.youtube.com/playlist?list=PLFPkAJFH7I0keB1qpWk5qVVUYdNLTEUs3
* MySQL => http://g2pc1.bu.edu/~qzpeng/manual/MySQL%20Commands.htm
*/
class Dbase {
public static $_instance = null;
private $_pdo, $_query, $_error = false, $_result, $_count = 0, $_lastInsertId = null, $_host = "localhost", $_db_name = "dbname",
$_username = "username", $_password = "password";
public function __construct() {
try {
$this->_pdo = new PDO("mysql:host=".$this->_host.";dbname=".$this->_db_name,$this->_username,$this->_password);
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function get_instance() {
if (!isset(self::$_instance)) {
self::$_instance = new Dbase();
}
return self::$_instance;
}
/*
* Query Execution
*/
public function query($sql, $params = []) {
$this->_error = false;
// prepare sql
if ($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
// count params
if (count($params)) {
foreach ($params as $param) {
$this->_query->bindValue($x,$param);
$x++;
}
}
// query execution
if ($this->_query->execute()) {
$this->_result = $this->_query->fetchALL(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastInsertId = $this->_pdo->lastInsertId();
} else {
$this->_error = true;
}
}
return $this;
}
/*
* Read Values in Database
*/
protected function _read($table,$params = []) {
$conditionString = '';
$operator = '';
$bind = [];
$order = '';
$limit = '';
// Plot Conditions
if (isset($params['conditions'])) {
if (is_array($params['conditions'])) {
$x = 0;
foreach($params['conditions'] as $condition) {
if (array_key_exists('operator',$params)) {
$operator = $params['operator'];
}
$conditionString .= ' '.$condition.' '.$operator[$x].' ? '.' AND';
$x++;
}
$conditionString = trim($conditionString);
$conditionString = rtrim($conditionString,', AND');
} else {
$conditionString = $params['conditions'];
}
}
if ($conditionString != '') {
$conditionString = ' WHERE '.$conditionString;
}
// Bind
if (array_key_exists('bind', $params)) {
$bind = $params['bind'];
}
// Order
if (array_key_exists('order', $params)) {
if ($params['order'] != '') {
$order = ' ORDER BY '.$params['order'];
}
}
// Limit
if (array_key_exists('limit', $params)) {
if ($params['limit'] != '') {
$limit = ' LIMIT '.$params['limit'];
}
}
$sql = "SELECT * FROM {$table}{$conditionString}{$order}{$limit}";
if ($this->query($sql,$bind)) {
if (!count($this->_result)) return false;
$this->count();
return $this->result();
}
return false;
}
/*
* Simple Select
*/
public function select($table,$condition,$operator,$bind,$order='',$limit='') {
$params = array();
$params['conditions'] = $condition;
$params['operator'] = $operator;
$params['bind'] = $bind;
$params['order'] = $order;
$params['limit'] = $limit;
return $this->_read($table,$params);
}
/*
* Like MySQL Statements
*/
public function like($table,$params = [],$before) {
}
/*
* Basic INSERT SQL Reference: INSERT INTO tablename (`fname`,`lname`) VALUES (?,?)
*/
public function insert($table, $fields = []) {
$fieldString = '';
$valueString = '';
$values = [];
foreach ($fields as $field => $value) {
$fieldString .= '`'.$field.'`,';
$valueString .= '?,';
$values[] = $value;
}
$fieldString = rtrim($fieldString,',');
$valueString = rtrim($valueString,',');
$sql = "INSERT INTO {$table} ({$fieldString}) VALUES ({$valueString})";
if (!$this->query($sql,$values)->error()) {
return true;
}
return false;
}
/*
* Basic UPDATE SQL Reference: UPDATE tablename SET `fname` = ? WHERE `id` = $id
*/
public function update($table, $fields = [], $where = []) {
$fieldString = '';
$values = [];
$whereString = '';
foreach ($fields as $field => $value) {
$fieldString .= '`'.$field.'`= ?,';
$values[] = $value;
}
foreach ($where as $w => $val_w) {
$whereString .= '`'.$w.'` = '.$val_w;
}
$fieldString = rtrim($fieldString,',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE {$whereString}";
if (!$this->query($sql,$values)->error()) {
return true;
}
return false;
}
/*
* Basic DELETE SQL Reference: DELETE FROM tablename WHERE `id` = $id
*/
public function delete($table,$fields = [] ) {
$fieldString = '';
$values = [];
foreach ($fields as $field => $value) {
$fieldString .= '`'.$field.'`= ?';
$values[] = $value;
}
$sql = "DELETE FROM {$table} WHERE {$fieldString}";
if (!$this->query($sql,$values)->error()) {
return true;
}
return false;
}
/*
* Generate Error
*/
public function error() {
return $this->_error;
}
/*
* Return result
*/
public function result() {
return $this->_result;
}
/*
* Return count
*/
public function count() {
return $this->_count;
}
}
@jason-napolitano
Copy link

Here is a PHP 7.4 version of your code. I hope people enjoy!

https://gist.github.com/jason-napolitano/6ef5ba92b62e39e952e6dd673d276eba

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment