I have a MySQL column ‘public’ that contains boolean values (aka tinyint, 1 or 0). When querying I generally don’t care about the value of the public column, so by default I pass an underscore (MySQL wildcard). In some instances though I only want rows that match “public = 0” or “public = 1” so I override the underscore with either 0 or 1. That’s not the clearest explanation I’ve ever given so here’s some code:
public function get_hunts($public = '_') {
$sth = $this->_db->prepare("SELECT * FROM hunts WHERE( user_id = :user AND public = :public)");
$sth->bindParam(':user', $this->_id);
$sth->bindParam(':public', $public);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
//get any result
get_results();
//get only public results
get_hunts(1)
Binding an underscore (I’ve also tried the general wildcard %) in this way causes the query to fail. What is a better way of achieving this?
To use any wildcard characters, you’d need to use a
LIKEcomparison instead of an equalsOtherwise, you’d need to take some kind of query builder approach where you build up the
WHEREconditions based on arguments to your function.