My boss makes us comment like this. Personally I think it's way too much, but it's what he wants, and he signs the pay check 😉
function build_query($input, $tablename, $method) {
/* This function builds a query from your sent variables.
It will exclude any variable names you add after the 3 required
parameters.
Usage:
$array = array("foo"=>"foo1", "bar"=>"bar1", "pie"=>"mmm, pie");
$sql = build_query($array, "table", "POST", "bar");
The resulting query will look like this:
"SELECT * FROM table WHERE foo='foo1' AND pie='mmm, pie'"
Created By Matt Magin.
*/
// Set the method variable to the proper string
switch(strtoupper($method)) {
case ('GET' || '_GET'):
$method = "_GET";
break;
case ('REQUEST' || '_REQUEST'):
$method = "_REQUEST";
break;
case ('SESSION' || '_SESSION'):
$method = "_SESSION";
break;
default:
$method = "_POST";
break;
}
// Get the number of function arguments
$num_args = func_num_args();
// Get the actual values of said arguments
$args = func_get_args();
// Loop through all keys in the chosen method array
foreach($$method as $k=>$v) {
// Unset the arg_exists boolean
unset($arg_exists);
/* Loop through the extra arguments, if it matches the value
set the arg_exists boolean and break out of the loop to decrease
the amount of processing */
for($i = 2; $i < $num_args; $i++) {
if($k == $args[$i]) {
$arg_exists = true;
break;
}
}
if(!isset($arg_exists)) {
/* If the argument didn't exist check to see if the where string is
empty, if it is, then append the first condition, else append the second */
$where_string .= ($where_string == "") ? " WHERE ($k='$v')" : " AND ($k='$v')";
}
}
// Build the whole query
$sql = "SELECT * FROM $tablename $where_string";
// Return the completed sql
return $sql;
}