Suppose my URL is http://something.com/products.php?brand=samsung&condition=new
For the above query I am using isset() and $_GET[]) functions along with lots of if-else statements in PHP to generate a sql query for displaying the products which satisfy the search criteria.
For example: if I am dealing with only brand and condition parameters then this is how I will generate the query:
$sql = "select * from products where 1=1 ";
if(isset($_GET['brand']))
{
if(isset($_GET['condition']))
{
$sql = $sql + "and brand=".$_GET['brand']." and condition=".$_GET['condition'];
}
}
else
{
if(isset($_GET['condition']))
{
$sql = $sql + "and condition=".$_GET['condition'];
}
else
{
$sql = $sql + ";";
}
}
Now suppose my URL is having 10 parameters (or more). In this case, using if-else is not at all good. How can I generate the query without using so many if-else statements? Is there any better method/script/library available for doing this thing?
There are a number of ways to do this, but the easiest way would be to loop through the acceptable columns and then append appropriately.
If you really are trying to get rid of the ‘if’ statements, you could use this:
But you may want to run actual benchmarks to determine whether that is a substantially better option.