$randomvariable = ESACPE_MYSQL_STRING($_GET['randomvariable']);
$search =
"SELECT * FROM objects " .
(empty($randomvariable) ? "" : "WHERE transactiontype='$randomvariable' ") .
"ORDER BY id DESC";
Where ESCAPE_MYSQL_STRING
is the relevant function for escaping strings for whatever MySQL driver you're using.
Another, more modular way:
$search = array(
"select" => "SELECT * FROM objects",
"where" => "WHERE transactiontype='$randomvariable'",
"order" => "ORDER BY id DESC"
);
if (empty($randomvariable)) {
unset($search["where"]);
}
$search = implode(' ', $search);
The nice thing about this is that you can add, remove or alter the query for any situation easily, having easy access to any part of the query.
You could also do this with CASE()
in SQL, but it's somewhat cumbersome and you shouldn't expect good performance either:
SELECT * FROM objects
WHERE transactiontype LIKE
CASE WHEN '$randomvariable' = '' THEN
'%'
ELSE
'$randomvariable'
END CASE
ORDER BY id DESC