public function createSQL($query) { // Build the query $sqlQuery = "select "; if (!empty($query["conditions"])) { if (isset($query["fields"])) { $sqlQuery .= join($query["fields"], ",") . " from " . $this->modelCache->getModelSource(); } else { $sqlQuery .= join($this->modelCache->getFieldsForQuery(), ",") . " from " . $this->modelCache->getModelSource(); } } else { $sqlQuery .= join($this->modelCache->getFieldsForQuery(), ",") . " from " . $this->modelCache->getModelSource(); $qTemp = $query; $single = $qTemp["limit"] == 1; unset($qTemp["limit"]); $query = array("conditions" => $qTemp); if ($single) { $query["limit"] = 1; } } $whereConditions = array(); if (!empty($query["conditions"])) { foreach ($query["conditions"] as $field => $value) { // First sanitize the value, if necessary $negation = false; $operator = "="; if (preg_match("/^!/", $field)) { $field = substr($field, 1); $negation = true; $operator = "="; } else { if (preg_match("/^</", $field)) { $operator = substr($field, 0, 1); $field = substr($field, 1); } else { if (preg_match("/^>/", $field)) { $operator = substr($field, 0, 1); $field = substr($field, 1); } } } if (is_array($value)) { // First see if this is a subquery if (!empty($value["subquery"])) { $subModel = new Model($value["target"]); $whereConditions[] = "{$field} " . ($negation ? "not" : "") . " in (" . $subModel->createSQL($value["subquery"]) . ")"; } else { $valueArray = array(); foreach ($value as $val) { $valueArray[] = $this->modelCache->sanitize($field, $val); } $whereConditions[] = "{$field} " . ($negation ? "not" : "") . " in (" . join($valueArray, ",") . ")"; } } else { $value = $this->modelCache->sanitize($field, $value); $whereConditions[] = "{$field} " . ($negation ? "!" : "") . "{$operator} {$value}"; } } $sqlQuery .= " where " . join($whereConditions, " AND "); // echo $sqlQuery; } if (!empty($query["order"])) { $sqlQuery .= " order by " . $query["order"]["field"] . " " . $query["order"]["sort"]; } if (!empty($query["limit"])) { $sqlQuery .= " limit " . $query["limit"] . (empty($query["offset"]) ? "" : ", " . $query["offset"]); } return $sqlQuery; }