Initial commit
This commit is contained in:
82
app/Core/QueryBuilder copy.php
Normal file
82
app/Core/QueryBuilder copy.php
Normal file
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
use PDO;
|
||||
|
||||
|
||||
class QueryBuilder {
|
||||
protected $pdo;
|
||||
protected $table;
|
||||
protected $where = [];
|
||||
protected $params = [];
|
||||
|
||||
public function __construct(PDO $pdo) {
|
||||
$this->pdo = $pdo;
|
||||
}
|
||||
|
||||
public function table($table) {
|
||||
$this->table = $table;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function where($column, $operator, $value = null) {
|
||||
if ($value === null) {
|
||||
$value = $operator;
|
||||
$operator = '=';
|
||||
}
|
||||
$paramName = 'where_' . str_replace('.', '_', $column) . '_' . count($this->params);
|
||||
|
||||
$this->where[] = "{$column} {$operator} :{$paramName}";
|
||||
$this->params[$paramName] = $value;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get() {
|
||||
$sql = "SELECT * FROM {$this->table}";
|
||||
if (!empty($this->where)) {
|
||||
$sql .= " WHERE " . implode(' AND ', $this->where);
|
||||
}
|
||||
|
||||
// echo "<b>SQL:</b> " . $sql . "<br><br>";
|
||||
// echo "<b>Params:</b><pre>"; print_r($this->params); echo "</pre>";
|
||||
// // die();
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->execute($this->params);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
public function insert(array $data) {
|
||||
$columns = implode(', ', array_keys($data));
|
||||
$placeholders = ':' . implode(', :', array_keys($data));
|
||||
|
||||
$sql = "INSERT INTO {$this->table} ({$columns}) VALUES ({$placeholders})";
|
||||
return $this->pdo->prepare($sql)->execute($data);
|
||||
}
|
||||
|
||||
public function update(array $data) {
|
||||
$fields = "";
|
||||
foreach ($data as $key => $value) {
|
||||
$fields .= "{$key} = :{$key}, ";
|
||||
}
|
||||
$fields = rtrim($fields, ', ');
|
||||
|
||||
$sql = "UPDATE {$this->table} SET {$fields}";
|
||||
if (!empty($this->where)) {
|
||||
$sql .= " WHERE " . implode(' AND ', $this->where);
|
||||
}
|
||||
return $this->pdo->prepare($sql)->execute(array_merge($data, $this->params));
|
||||
}
|
||||
|
||||
public function delete() {
|
||||
$sql = "DELETE FROM {$this->table}";
|
||||
if (!empty($this->where)) {
|
||||
$sql .= " WHERE " . implode(' AND ', $this->where);
|
||||
}
|
||||
|
||||
return $this->pdo->prepare($sql)->execute($this->params);
|
||||
}
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user