92 lines
2.5 KiB
PHP
92 lines
2.5 KiB
PHP
<?php
|
|
|
|
use PDO;
|
|
|
|
Class Database{
|
|
global $db_config;
|
|
private $pdo;
|
|
private $type;
|
|
private $table;
|
|
private $columns;
|
|
private $where;
|
|
private $limit;
|
|
private $query;
|
|
|
|
public function __construct(){
|
|
$this->pdo = new PDO('mysql:host=' . $db_config['host'] . ';dbname=' . $db_config['database'] . ';charset=utf8mb4', $db_config['username'], $db_config['password']);
|
|
}
|
|
|
|
public function select($columns = "*"){
|
|
$this->type = "SELECT";
|
|
$this->columns = $columns;
|
|
}
|
|
|
|
public function from($table){
|
|
$this->table = $table;
|
|
}
|
|
|
|
public function where($key, value){
|
|
$this->where = array($key, $value);
|
|
}
|
|
|
|
public function andWhere($key, value){
|
|
if(!$this->where) $this->where = array();
|
|
$this->where[$key] = $value;
|
|
}
|
|
|
|
public function limit($number){
|
|
$this->limit = $number;
|
|
}
|
|
|
|
public function all(){
|
|
$this->query = $this->type . ' ' . $this->columns . ' FROM ' . $this->table;
|
|
|
|
if(!empty($this->where)){
|
|
$whereClauses = [];
|
|
foreach($this->where as $condition){
|
|
$whereClauses[] = $condition[0] . ' = :"' . $condition[0];
|
|
}
|
|
$this->query .= ' WHERE ' . implode(' AND ', $whereClauses);
|
|
}
|
|
|
|
if(!empty($this->limit)){
|
|
$this->query .= ' LIMIT ' . $this->limit;
|
|
}
|
|
|
|
$results = $this->pdo->prepare($Query);
|
|
foreach($this->where as $condition){
|
|
$results->bindValue(':' . $condition[0], $condition[1]);
|
|
}
|
|
|
|
$results->execute();
|
|
return $results->fetchAll();
|
|
}
|
|
|
|
public function one(){
|
|
$this->query = $this->type . ' ' . $this->columns . ' FROM ' . $this->table;
|
|
|
|
if(!empty($this->where)){
|
|
$whereClauses = [];
|
|
foreach($this->where as $condition){
|
|
$whereClauses[] = $condition[0] . ' = :"' . $condition[0];
|
|
}
|
|
$this->query .= ' WHERE ' . implode(' AND ', $whereClauses);
|
|
}
|
|
|
|
$this->query .= " LIMIT " . $this->limit;
|
|
|
|
$results = $this->pdo->prepare($Query);
|
|
foreach($this->where as $condition){
|
|
$results->bindValue(':' . $condition[0], $condition[1]);
|
|
}
|
|
|
|
$results->execute();
|
|
return $results->fetch();
|
|
}
|
|
}
|
|
|
|
// Database::select(id, name)->from('tablename')->all()
|
|
// Database::select(id, name)->from('tablename')->limit(100)->all()
|
|
// Database::select()->from('tablename')->where('id', 3)->one()
|
|
|
|
?>
|