<?
function bq($a, $preview = false) {
# Version 1.1
# Copyright Jonas Eklundh Communication AB 2008
if (count((array)$a["select"]) == 0) return false;
if (count((array)$a["from"]) == 0) return false;
if (!is_array($a["from"])) $a["from"] = preg_split("/,s+/", $a["from"]);
if (!is_array($a["select"])) {
preg_match_all('#s*((?:([^)]+)|[^,])+)s*#s', $a["select"], $m);
$a["select"] = $m[1];
}
$query[] = "select " . join(", ", $a["select"]);
$query[] = "from " . join(", ", $a["from"]);
if ($a["join"]) {
foreach($a["join"] as $dir => $ar) {
unset($ons);
foreach($ar["on"] as $one => $two) {
$ons[] = bq_eq($one, "=", $two);
}
$dir = is_numeric($dir) ? "" : "$dir ";
if ($ar["dir"]) $dir = $ar["dir"] . " ";
$query[] = "{$dir}join ($ar[db]) on (" . join(" AND ", $ons) . ")";
}
}
if ($a["where"]) {
$query[] = "where";
foreach($a["where"] as $k => $v) {
unset($eq);
if (is_array($v)) {
unset($ors);
$v = array_filter($v);
if (preg_match("!(.*?):(.*)!i", $k, $m)) {
$k = $m[1];
$eq = $m[2];
}
if ($eq == "in" || $eq == "not in") {
$wheres[] = "$k $eq('" . join("', '", $v) . "')";
} else {
foreach($v as $key => $value) {
if (is_numeric($key) && $eq) $key = $k;
$oreq = "=";
if (preg_match("!(.*?):(.*)!i", $key, $m)) {
$key = $m[1];
$oreq = $m[2];
}
# 2010-09-02 ##################################
# Detta var bortkommenterat men det ska ju
# fungra så här, väl?
###############################################
if ($oreq == "in" || $oreq == "not in") {
$ors[] = "$key $oreq('" . join("', '", $value) . "')";
} else {
$ors[] = bq_eq($key, $oreq, $value);
}
}
$a_eq = $eq ? $eq : $k;
$wheres[] = "(" . join(" $a_eq ", $ors) . ")";
}
} else {
if (is_numeric($k)) {
$wheres[] = $v;
} else {
$eq = "=";
if (preg_match("!(.*?):(.*)!i", $k, $m)) {
$k = $m[1];
$eq = $m[2];
}
$wheres[] = bq_eq($k, $eq, $v);
}
}
}
$query[] = join(" and ", $wheres);
}
if ($a["group"]) {
$query[] = "group by " . clean_keyword($a["group"]);
}
if ($a["order"]) {
if (is_array($a["order"])) {
foreach($a["order"] as $k => $v) {
if (is_numeric($k)) {
$order[] = clean_keyword($v);
}
else {
$v = clean_keyword($v);
$k = clean_keyword($k);
$order[] = "$k $v";
}
}
$query[] = "order by " . join(", ", $order);
}
else {
#$order = clean_keyword($a["order"]);
$order = $a["order"];
$query[] = "order by $order";
}
}
if ($a["limit"]) {
$query[] = "limit " . clean_keyword($a["limit"]);
}
$query = join(" ", $query);
return $preview ? notice($query) : $query;
}
?>
Note that the below code is the exact code that I am using and may use functions that are exclusive to my system, and as such may not be suitable for copy/paste. Plus, these functions can change at any time and any blogs/tutorials that depend on these functioning in a specific way may have changed since it was written. If such a discrepancy is found, please email me at
If the function "lp()" is used, it's my "Language Print" function, that translates phrases from english to the site language. So, instead of "lp('and')" you would use just "and".