I have a simple php mysql search that searches a database, however, i cannot seem to get it to search the text from the search field and the category, but i only want it to search the category if selected,
this is my code that i have tried:
if ($search !== null){
$sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE) ORDER BY price ".$price." LIMIT ".$start.", ".$limit;
$q = $conn->prepare($sql) or die("failed!");
// Bind the params to the placeholders
$q->bindParam(':search', $search, PDO::PARAM_STR);
$q->execute();
}
if ($search !== null && $category !== null){
$sql = "SELECT * FROM people WHERE MATCH (lname,fname) AGAINST (:search IN BOOLEAN MODE) and category=:category ORDER BY price ".$price." LIMIT ".$start.", ".$limit;
$q = $conn->prepare($sql) or die("failed!");
// Bind the params to the placeholders
$q->bindParam(':search', $search, PDO::PARAM_STR);
$q->bindParam(':category', $category, PDO::PARAM_STR);
$q->execute();
}
however, this still ignores the category field option if selected! any ideas?
they are being set as follows:
// Check and set category
$category = (!empty($_GET['category']) ? $_GET['category'] : null);
// Check and set search
if(!empty($_GET['search'])){
$search = $_GET['search'];
}else{
$search = null;
}
Do some debugging to make sure
$searchand$categoryare being set. That is most likely your problem. From the looks of it,$categoryshould be getting set (since you said its coming from query string), but just check both to be sure. Something like:If users are accessing this page from a link (
<a href="search.php?category=Books">Books?</a>), I don’t see how$_GET['search']would be set.I would suggest you change your
ifstatements to be more efficient (only 1 should get executed):Also, I would use
isset()to check if these variables are instantiated instead ofempty().