Jump to content

Can the OR keyword be used for same field in a mysql table?


drayarms

Recommended Posts

I'm trying to create a search form where members of a site can search other members whose user information is stored in a mysql database.  One of the search parameters is gender which searches for records from a column in the database called gender where members can either have the value "man" or "woman".  The user can choose between 3 options from a pull down menu named gender (man, woman, both).  Then I'm thinking about using a select query to search the database upon submission of the form, which goes something like this:


$sql= SELECT* FROM members WHERE gender ='{$_POST['gender']}' ;

Now I can easily assign the value "man" for the option man in the pull down menu and "woman for the option woman, to match their corresponding names in the database.  The problem lies with the "both" option which has to be either man or woman.  I'm thinking about assigning it the value "man OR woman" so that when the form is submitted, the query would read: SELECT*FROM members WHERE gender ='{$_POST[man OR woman']};

I just don't know if this would be a right usage of the OR keyword and if such a query would work.  Before trying it out, I'd like to know if this makes any sense and if not, what's an alternative way to work around this?

@Pikachu

 

Well I forgot to mention that there are other search parameters besides gender.  Take for example lets say I had to search for gender AND interest.  That compels me to specify the WHERE clause for both columns right? With that in mind, how would I handle this?

Build the query string dynamically. Check the values coming from the form and construct it conditionally, based on those. Here's a start:

 

$query = 'SELECT `field` FROM `table`';
$where = array();
if( $_POST['gender'] != 'both' ) {
$where[] = mysql_real_escape_string($_POST['gender']);
}
if( !empty($_POST['interest']) ) {
$where[] = mysql_real_escape_string($_POST['interest']);
}

if( count($where) > 0) {
$query .= ' WHERE ' . implode(' AND ', $where);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.