I've made a simple querybuilder for my job, but I'm kind of insecure about starting to use it because I'm afraid of errors happening when I start using it. I've done some tests with where
, join
, etc... So far I didn't find anything, but if someone could take a look and see if there's something missing, I would appreciate it a lot.
Is this class reliable enough?
P.S.: I've only made it work for SELECT
queries because it's the only thing I need.
P.P.S.: I know I could use a external lib, but it is worth nothing trying to make one myself. (And libs are kind of overwhelming for what I need)
<?php
class QueryBuilder {
private $query;
private $table;
public function __constructor() {
$this->query = '';
$this->table = null;
}
public function __call($method, $arguments) {
$index = 1;
preg_match('/where/i', $method, $isWhere);
if(!empty($isWhere) && strlen($method) > 6) {
$method = str_ireplace($isWhere[0], '', $method);
}
preg_match_all('/[A-Z]/', $method, $temp, PREG_OFFSET_CAPTURE);
$temp = $temp[0];
if(!empty($temp)) {
foreach($temp as $offset) {
if($offset > 1 || $offset[1] > 0) {
$this->query .= strtoupper(substr_replace($method, ' ', $offset[1], 0));
$this->query .= ' ';
}
}
}
else {
$this->query .= strtoupper($method);
$this->query .= ' ';
}
if(count($arguments) == 1) {
if(!empty($arguments)) {
foreach($arguments as $arg) {
foreach($arg as $key => $value) {
$this->query .= $value;
if($index < count($arg))
$this->query .= ', ';
else
$this->query .= ' ';
}
}
}
}
else {
if(!empty($arguments)) {
$this->query .= $arguments[0];
$this->query .= ' ON ';
unset($arguments[0]);
foreach($arguments as $arg) {
foreach($arg as $key => $value) {
$this->query .= $value;
if($index < count($arg))
$this->query .= ', ';
else
$this->query .= ' ';
}
}
}
}
return $this;
}
public function table($tables = []) {
$index = 1;
if($tables === null || empty($tables)) {
throw new Exception('Table value cannot be null.');
return;
}
foreach($tables as $table) {
$this->table .= $table;
if($index < count($tables)) {
$this->table .= ', ';
}
else {
$this->table .= ' ';
}
}
return $this;
}
public function select($cols = null) {
$index = 1;
$this->query .= 'SELECT ';
if($cols === null || empty($cols) || $cols == '') {
$this->query .= ' * ';
}
else {
foreach($cols as $value) {
$this->query .= $value;
if($index < count($cols)) {
$this->query .= ', ';
}
$index++;
}
}
$this->query .= ' FROM '.$this->table;
return $this;
}
private function makeQuery() {
return $this->query;
}
public function get() {
return $this->makeQuery();
}
}
$test = new QueryBuilder();
echo $test
->table()
->select(['id', 'name'])
->Where(['name= \'john\''])
->whereNotIn(['id > 1'])
->get();