Reputation: 327
I have a two tables:
Then in the search form I have three fields:
Depending on the choices of the form field it will make a search from the two tables.
I'm thinking in doing multiple SQL querys depending on the user choices.
The problem is that maybe the user will not fill the input form with the name of the client, or maybe it will, but will not choose a city, etc.
So will I have to do multiple ifs to show multiple sql querys depending on user choice? maybe I have a less confusing solution...
Upvotes: 1
Views: 2094
Reputation: 46997
Perhaps your database structure could be altered to help you. For example, I assume you have a relationship between Cities and Clients. It sounds like Businesses is something like "Tech" or "Search" in which case could you have multiple clients with the same Business? Could be worth porting businesses to a separate table and then referring to those. Then you can have a simple query such as:
SELECT *
FROM clients
WHERE clients.city = {form result: cities.id}
AND clients.business = {form result: businesses.id}
ORDER BY clients.name
LIMIT 0, 30
Now assuming the user does not fill in one of the fields (e.g. city) you have two choices: force them to fill it in by validating user input or use it as a wildcard, in which case you could remove the WHERE clients.city
clause from your query. Assuming you're giving your <select>
options values of an id
from Cities.
Programmatically I'd build the query in this case:
$queryStr = 'SELECT * FROM clients';
if (!empty($_POST['city']) && !empty($_POST['business'])) {
$queryStr .= ' WHERE city = ' . filter($_POST['city']) . ' AND business = ' . filter($_POST['business']);
} elseif (!empty($_POST['city'])) {
$queryStr .= ' WHERE city = ' . filter($_POST['city']);
} elseif (!empty($_POST['business'])) {
$queryStr .= ' WHERE business = ' . filter($_POST['business']);
} else {
// pass
}
$queryStr .= ' ORDER BY name LIMIT 0, 30';
Where filter is your choice of filtering method.
Upvotes: 2
Reputation: 13816
Simply query the DB with your criteria. If clients/cities actually exist, then they'll show up, otherwise the query will return an empty set. Easy as that, no need to validate the existence of either of them - the user should be smart enough to be able to come up with an existing city name for example.
The only thing you need to do is to mysql_real_escape_string().
Upvotes: 1