don
don

Reputation: 4522

MySql "WHERE" builder

I was thinking of implementing a function to "build" the WHERE clause in an SQL request like so:

"SELECT * FROM table $where"

Building $where with a cycle that would look like this:

$arr=array("Id"=>"1","Time"=>"12:00");
function whereBuild($arr){
    foreach ($arr as $key => $val){
      $result.=$key.'="'.$val.'" AND ';
    }
    $result = substr($result, 0, -5); // removes last AND and spaces
    return $result
}
$where = whereBuild($arr);

What do you think? Does it make any sense? Could it be achieved in a simpler/better way?

Thank's!

Upvotes: 2

Views: 113

Answers (1)

Aaron W.
Aaron W.

Reputation: 9299

If you are always using AND in your query you can build an array and implode it on return.

$arr = array("Id"=>"1","Time"=>"12:00");
function whereBuild($arr){
    $result = array();
    foreach ($arr as $key => $val){
      $result[] = $key.'="'.$val.'"';
    }
    return implode(" AND ", $result);
}
$where = whereBuild($arr);

Upvotes: 5

Related Questions