Jump to content

search using checkboxes


silverglade

Recommended Posts

Hi, I was wondering if anyone knows how I might do a search in a database from a form using checkboxes, where the code is like this below please? I want to do a database query like this, if firstname is checked, and gender is checked. I want to find someone in the database with that gender and first name only. If all of them are checked, find all matches to that criteria. I think this might be a lot harder than I describe, but that is what I need to do. like this

 

mysql_query("SELECT  users WHERE gender LIKE '%gender%, OR firstname LIKE....."

 

 

Search the database by:
<form action="search.php" method="post">
  <p>
    <input type="checkbox" name="firstname2" size="20" id="firstname2" value="firstname2" /> 
    First Name<br/>
    <input type="checkbox" name="lastname2" size="20" id="lastname2" value="lastname2" /> 
    Last Name<br/>
    <input type="checkbox" name="dob2" size="20" id="dob2" value="dob2" /> 
    Date of Birth<br/>
    <input type="checkbox" name="gender2" size="20" id="gender2" value="gender2" /> 
    Gender<br/>
  <input type="submit" name="search" value="Search" />  <input type="reset" name="reset" value="reset" />

</form>

Link to comment
Share on other sites

Untested. I believe this is what you're looking for?

 

<?php
if (empty($firstname) AND empty($lastname) AND empty($dob) AND empty($gender))
{
die('You must check one of the following boxes');
}

$sql_where_clause = '';
if (!empty($firstname))
{
$sql_where_clause .= 'firstname LIKE ' . $firstname . ' AND';
}

if (!empty($lastname))
{
$sql_where_clause .= 'lastname LIKE ' . $lastname . ' AND';
}

if (!empty($dob))
{
// I'm assuming date of birth is a string here
$sql_where_clause .= 'dob LIKE ' . $dob . ' AND';
}

if (!empty($gender))
{
// I'm assuming gender is a string here (should be enum really)
$sql_where_clause .= 'gender LIKE ' . $gender . ' AND';
}
$sql_where_clause = mysql_real_escape_string(rtrim($sql_where_clause, ' AND'));

$query = "SELECT users WHERE $sql_where_clause";
mysql_query($query);
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.