Reputation: 2000
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;
}
Upvotes: 0
Views: 1078
Reputation: 26167
Do some debugging to make sure $search
and $category
are being set. That is most likely your problem. From the looks of it, $category
should be getting set (since you said its coming from query string), but just check both to be sure. Something like:
if($category !== null)
die("category = $category");
else {
die("no category");
}
//do same test for $search
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 if
statements to be more efficient (only 1 should get executed):
if ($search !== null){
if($category !== null){
//query with category
}
else {
//query w/o category
}
}
Also, I would use isset()
to check if these variables are instantiated instead of empty()
.
Upvotes: 1