I’m working with raw SQL in PHP. What’s a good way of building statements with optional parameters? For example, I need to filter user profiles with criteria such as gender, age and origin. In what form would it be best to pass parameters like these?
Here’s my current approach:
$params = "";
if( isset($_GET["gender"]) ){
$gender = "";
switch( $_GET["gender"] ){
case "male":
$gender = " WHERE users.gender = 1 ";
break;
case "female":
$gender = " WHERE users.gender = 0 ";
break;
}
$params = $params + $gender;
}
If you are determined to use raw SQL you could roll your own very simple query builder.
There are a number of libraries that do this for you but the basic principle would be to create an object that knows about your ‘base query’ then set a series of parameters on that object .Then write a method for building your SQL statement according to those parameters.
This might be as simple as setting an array of clauses and then imploding them with an ‘AND’ statement between them…