Reputation: 5
I have created an HTML form with a search box and a drop down list of 50 states in the USA. What I want is to let the user type in a keyword in the search box (email, subject, username, etc.) and select a state from the drop down. By selecting a state from the drop down, I want my PHP code to find the keyword from the search box only in that selected state. For example as a user, I would like to find "soccer" in the state of Washington and see a list of results.
In other words, how would I display results only in the selected state combined with my search form?
Here is a bit of my PHP code to give you all an idea of what I'm trying to accomplish.
// this is pulling the text that was typed in the html search box
$searchbox = $_POST['searchbox'];
// this is pulling the state from my HTML drop down menu
$state = $_POST['state'];
$searchboxresult = mysql_query("
SELECT *
FROM table
WHERE (ID LIKE '%".$_POST['searchbox']."%')
OR (stateID LIKE '%".$_POST['searchbox']."%')
OR (city LIKE '%".$_POST['searchbox']."%')
OR (subject LIKE '%".$_POST['searchbox']."%')
OR (email LIKE '%".$_POST['searchbox']."%')
OR (posting LIKE '%".$_POST['searchbox']."%')
OR (skill LIKE '%".$_POST['searchbox']."%')
OR (event LIKE '%".$_POST['searchbox']."%')
OR (days LIKE '%".$_POST['searchbox']."%')
OR (url LIKE '%".$_POST['searchbox']."%')
");
// and
$statedropdownresult = mysql_query("
SELECT * FROM table WHERE stateID LIKE '%$state%'
");
Then I have a while loop that searches for everything and outputs the data. But I can't get the states drop down to limit what the user is searching for. I can only get one or the other mysql_query to work in combination with my while loop, not both. For some reason, combining the queries into one using AND doesn't seem to work either. Any ideas?
I know that the code is sloppy and there are security issues, however I will be going through to do a cleanup later on. If you need more details or clarification on something, I would be happy elaborate more!
Upvotes: 0
Views: 2889
Reputation: 4217
You could try something like this:-
$sql ="SELECT * FROM table WHERE 1";
if($_POST['searchbox'] != ''){
$sql =" and (ID LIKE '%".$_POST['searchbox']."%') OR (stateID LIKE
'%".$_POST['searchbox']."%') OR (city LIKE '%".$_POST['searchbox']."%') OR
(subject LIKE '%".$_POST['searchbox']."%') OR (email LIKE
'%".$_POST['searchbox']."%') OR (posting LIKE '%".$_POST['searchbox']."%') OR
(skill LIKE '%".$_POST['searchbox']."%') OR (event LIKE
'%".$_POST['searchbox']."%') OR (days LIKE '%".$_POST['searchbox']."%') OR (url
LIKE '%".$_POST['searchbox']."%')";
}
if($state != ''){
$sql .= " and stateID LIKE '%".$state."%'";
}
mysql_query($sql);
Hope this helps.
Upvotes: 1