How can I write this PHP code better? It puts together an SQL query string from user input. The task is to return search results based on one or more text fields. The user can determine if partial matches are allowed.
$compop = $allowpartial ? "LIKE" : "="; // use LIKE for wildcard matching
$any = $allowpartial ? "%" : ""; // SQL uses % instead of * as wildcard
$namecondstr = ($name === "") ? "TRUE" : ("Name $compop '$any$name$any'");
$citycondstr = ($city === "") ? "TRUE" : ("City $compop '$any$city$any'");
$itemnocondstr = ($itemno === "") ? "TRUE" : ("ItemNo $compop '$any$itemno$any'");
$ordernocondstr = ($orderno === "") ? "TRUE" : ("OrderNo $compop '$any$orderno$any'");
$serialcondstr = ($serial === "") ? "TRUE" : ("Serial $compop '$any$serial$any'");
$sortstr = ($name !== "") ? "Name" :
(($city !== "") ? "City" :
(($itemno !== "") ? "ItemNo" :
(($orderno !== "") ? "OrderNo" :
"Serial")));
$query = "SELECT * From Licenses
LEFT JOIN Items
ON Licenses.LicenseID = Items.LicenseID
WHERE $namecondstr
AND $citycondstr
AND $itemnocondstr
AND $ordernocondstr
AND $serialcondstr
ORDER BY $sortstr, Licenses.LicenseID";