PDO Database Connection Class with Query Builder
Advanced database class with query builder interface and prepared statements
0
PHP Code
<?php
class DB {
private static $instance = null;
private $pdo;
private $query;
private $error = false;
private $results;
private $count = 0;
private function __construct() {
try {
$this->pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
} catch(PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
}
public static function getInstance() {
if(!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function query($sql, $params = []) {
$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();
$this->count = $this->query->rowCount();
} else {
$this->error = true;
}
}
return $this;
}
public function action($action, $table, $where = []) {
if(count($where) === 3) {
$operators = ["=", ">", "<", ">=", "<=", "<>", "LIKE", "NOT LIKE"];
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, [$value])->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action("SELECT *", $table, $where);
}
public function delete($table, $where) {
return $this->action("DELETE", $table, $where);
}
public function insert($table, $fields = []) {
$keys = array_keys($fields);
$values = "";
$x = 1;
foreach($fields as $field) {
$values .= "?";
if($x < count($fields)) {
$values .= ", ";
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode("`, `", $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return $this->pdo->lastInsertId();
}
return false;
}
public function update($table, $id, $fields) {
$set = "";
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ", ";
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
return $this->results;
}
public function first() {
return $this->results()[0] ?? null;
}
public function count() {
return $this->count;
}
public function error() {
return $this->error;
}
}
Explanation
This Database class implements the Singleton pattern and provides a fluent query builder interface. It handles all CRUD operations with prepared statements to prevent SQL injection. The action() method provides a flexible way to build queries with operators.