amdp3-metaforums/Application/Foundations/QueryBuilder.php

109 lines
3.1 KiB
PHP
Raw Normal View History

2019-11-18 13:33:45 +00:00
<?php
namespace Application\Foundations;
class QueryBuilder {
private $query = "";
private $where = "";
2019-11-19 03:36:39 +00:00
private $misc = "";
2019-11-18 13:33:45 +00:00
public function select($fields) {
if(!is_array($fields)) {
$this->query .= "SELECT ".$fields;
} else {
$this->query .= "SELECT ".implode(",",SQLHelper::encode_list($fields));
}
return $this;
}
2019-11-19 03:36:39 +00:00
public function orderBy($column, $order = 'asc') {
$this->misc .= " ORDER BY ".$column." ".strtoupper($order);
return $this;
}
2019-11-18 13:33:45 +00:00
public function delete() {
$this->query .= "DELETE";
return $this;
}
public function update($table) {
// TODO: SQL injection
$this->query .= "UPDATE ".$table;
return $this;
}
public function set($data) {
$this->query .= " SET";
$final = [];
foreach($data as $key => $value) {
$final[] = $key." = ".SQLHelper::encode_literal($value);
}
$this->query .= " ".implode(",",$final);
return $this;
}
public function from($table) {
// TODO: SQL injection
2019-11-19 03:36:39 +00:00
$this->query .= " FROM `".$table."`";
2019-11-18 13:33:45 +00:00
return $this;
}
public function where($a, $b, $c = null) {
$field = "";
$value = "";
$operator = "=";
if($c == null) {
// 2 param syntax
$field = $a;
$value = $b;
} else {
$field = $a;
$value = $c;
$operator = $b;
}
$value = SQLHelper::encode_literal($value);
if($this->where == "") {
$this->where .= " WHERE ".$field." ".$operator." ".$value;
} else {
$this->where .= " AND ".$field." ".$operator." ".$value;
}
return $this;
}
2019-11-19 03:36:39 +00:00
public function whereIn($a, $b) {
$field = $a;
$value = SQLHelper::encode_list($b);
if($this->where == "") {
$this->where .= " WHERE ".$field." IN (".implode(",",$value).")";
} else {
$this->where .= " AND ".$field." IN (".implode(",",$value).")";
}
return $this;
}
public function whereNotIn($a, $b) {
$field = $a;
$value = SQLHelper::encode_list($b);
if($this->where == "") {
$this->where .= " WHERE ".$field." NOT IN (".implode(",",$value).")";
} else {
$this->where .= " AND ".$field." NOT IN (".implode(",",$value).")";
}
return $this;
}
2019-11-18 13:33:45 +00:00
public function orWhere($a, $b, $c = null) {
$field = "";
$value = "";
$operator = "=";
if($c == null) {
// 2 param syntax
$field = $a;
$value = $b;
} else {
$field = $a;
$value = $c;
$operator = $b;
}
2019-11-19 03:36:39 +00:00
$value = SQLHelper::encode_literal($value);
2019-11-18 13:33:45 +00:00
if($this->where == "") {
$this->where .= " WHERE ".$field." ".$operator." ".$value;
} else {
$this->where .= " OR ".$field." ".$operator." ".$value;
}
return $this;
}
public function build() {
2019-11-19 03:36:39 +00:00
return $this->query.$this->where.$this->misc;
2019-11-18 13:33:45 +00:00
}
}