Skip to content

Instantly share code, notes, and snippets.

@k4ml
Created November 11, 2010 22:06
Show Gist options
  • Save k4ml/673289 to your computer and use it in GitHub Desktop.
Save k4ml/673289 to your computer and use it in GitHub Desktop.
Generic SQL query builder
<?php
class QBuilderCondition {
protected $conjunction = 'AND';
protected $wheres = array();
public function __construct($conjunction = 'AND') {
$this->conjunction = $conjunction;
}
public function condition($field, $value = NULL, $operator = '=') {
if ($field instanceof QBuilderCondition) {
$this->wheres[] = $field;
}
else {
$this->wheres[] = $field .' '. $operator .' '. "'$value'";
}
return $this;
}
public function compile() {
$wheres = '';
$count = 0;
foreach ($this->wheres as $where) {
if ($where instanceof QBuilderCondition) {
$wheres .= $where->compile();
}
else {
if ($count > 0) {
$wheres .= ' '. $this->conjunction .' '. $where;
}
else {
$wheres .= ' '. $where;
}
}
$count++;
}
return ' AND ('. $wheres .' )';
}
public function get_conjunction() {
return $this->conjunction;
}
}
class QBuilder {
protected $base_table = '';
protected $tables = array();
protected $wheres = array();
public function select($table, $alias = NULL, $options = array()) {
if (!$alias) {
$table = $table .' '. $table;
}
else {
$table = $table .' '. $alias;
}
$this->base_table = $table;
return $this;
}
public function condition($field, $value = NULL, $operator = '=') {
if ($field instanceof QBuilderCondition) {
$this->wheres[] = $field;
}
else {
$this->wheres[] = $field .' '. $operator .' '. "'$value'";
}
return $this;
}
public function sql() {
$sql = "SELECT * FROM ". $this->base_table ."\n".
" WHERE \n\t".
$this->compile_where();
return $sql;
}
protected function compile_where() {
$wheres = '';
$count = 0;
foreach ($this->wheres as $where) {
if ($where instanceof QBuilderCondition) {
$wheres .= $where->compile();
}
else {
if ($count > 0) {
$wheres .= ' AND '. $where;
}
else {
$wheres .= ' '. $where;
}
}
$count++;
}
return $wheres;
}
public function __toString() {
return $this->sql();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment