I think it's quite a simple question. Is this my best bet or is there a 'proper' way of doing this?
<?php
$correctOrder = array("name", "address", "phone", "starttime", "endtime",
"status", "details");
$sql->sql1 = "SELECT * FROM `pickups` WHERE";
if (isset($_GET["name"])){
$sql->sql2 = "`name` LIKE '%" . $_GET['name'] . "%'";
}
if (isset($_GET["address"])){
if (!isset($_GET['name'])){
$q = "`address` LIKE '%" . $_GET['address'] . "%'";
} else {
$q = "AND `address` LIKE '%" . $_GET['address'] . "%'";
}
$sql->sql3 = $q;
}
...
...
echo implode(" ", (array) $sql);
?>
So, right now:
?name=Jari%20Martikainen&address=some%20random%20street
and
?name=Jari%20Martikainen&address=some%20random%20street&blah=har
and
?address=some%20random%20street&blah=har&name=Jari%20Martikainen
all return the same result which is desired, but it just doesn't seem like a very efficient way of doing things.
Build an array ($ands
) of AND clauses, but without the "AND".
$ands = array();
if (...)
$ands[] = "name LIKE ...";
if (...)
$ands[] = "address LIKE ...";
...
Then build the query:
$query = "SELECT ... WHERE " . implode(' AND ', $ands);
I find this pattern to be simple, clean, and avoids kludges like 1=1
or removing the extra AND
.