<?php
class MyQuery
{
var $action;
var $fields;
var $tables;
var $conditions;
var $orders;
var $groups;
var $updates;
var $inserts;
var $query;
function MyQuery()
{
$this->initVars();
}
function initVars()
{
$this->action='';
$this->fields = array();
$this->tables = array();
$this->conditions = array();
$this->orders = array();
$this->groups = array();
$this->updates = array();
$this->inserts = array();
$this->query = '';
}
function setAction($action)
{
$this->action = $action;
}
function setField($field,$as='')
{
if ($as == '') {
$this->fields[] = $field;
} else {
$this->fields[] = $field.' AS '.$as;
}
}
function setTable($table,$as='')
{
if ($as == '') {
$this->tables[] = $table;
} else {
$this->tables[] = $table.' AS '.$as;
}
}
function setOrder($field,$order)
{
$this->orders[] = $field.' '.$order;
}
function setGroup($field)
{
$this->groups[] = $field;
}
function setCondition($condition)
{
$this->conditions[] = $condition;
}
function setUpdate($field,$value)
{
$this->updates[] = $field."='".$value."'";
}
function setInsert($field,$value)
{
$this->inserts[] = array($field,"'".$value."'");
}
function getGroups()
{
if (sizeof($this->groups)>0) {
return 'GROUP BY '.join($this->groups, ', ').' ';
} else {
return '';
}
}
function getFields()
{
if (sizeof($this->fields)>0) {
return join($this->fields, ', ').' ';
} else {
return '* ';
}
}
function getTables()
{
if (sizeof($this->tables>0)) {
return join($this->tables,', ').' ';
} else {
return false;
}
}
function getUpdates()
{
if (sizeof($this->updates)>0) {
return 'SET '.join($this->updates,', ').' ';
} else {
return false;
}
}
function getConditions()
{
if (sizeof($this->conditions)>0) {
return 'WHERE '.join($this->conditions,' AND ').' ';
} else {
return '';
}
}
function getOrders()
{
if (sizeof($this->orders)>0) {
return 'ORDER BY '.join($this->orders,', ').' ';
} else {
return '';
}
}
function getInserts()
{
$f = array();
$v = array();
foreach ($this->inserts as $ins) {
list($field, $value) = $ins;
$f[] = $field;
$v[] = $value;
}
if (sizeof($f)==sizeof($v) && sizeof($f)>0) {
return '('.join($f,', ').') VALUES ('.join($v,', ').') ';
} else {
return false;
}
}
function getQuery()
{
switch (strtoupper($this->action)) {
case 'SELECT': {
$this->query = 'SELECT '.$this->getFields().'FROM '.$this->getTables().$this->getConditions().$this->getGroups().$this->getOrders();
break;
}
case 'INSERT': {
$this->query = 'INSERT INTO '. $this->getTables() . $this->getInserts();
break;
}
case 'UPDATE': {
$this->query = 'UPDATE '.$this->getTables() . $this->getUpdates() . $this->getConditions();
break;
}
case 'DELETE': {
$this->query = 'DELETE FROM '.$this->getTables() . $this->getConditions();
break;
}
default: {
return false;
}
}
return $this->query;
}
}
?>