There's a much simper way to do this.
create this prepared statement:
select * from mytable
where status = ? and (userid = ? or ?)
and (location = ? or ?)
order by `date` desc, time desc
limt ?
and pass the args to bind like this:
$stmt = $mysqli->prepare( [statement above] );
$stmt->bind_param( "siiiii",
"active", $userid, $userid == "ALL",
$location, $location == "ALL",
$limit);
The predicate (user_id = ? or ?)
will be true when the user_id equals the first replaced parameter, or when the second replaced parameter is true.
$user_id
when converted to an int will be its value when it's a string representation of a number, or zero otherwise. The expression $userid == "ALL"
will evaluate to a boolean, which will be passed to bind_param
. We can't tell bind_param
that a parameter is a boolean (the format string only understand string, int, double, and blob), so bind_param will convert the boolean to an int, which works for us.
As long as no user_id or location_id in the database is zero, you're fine.