I\'m trying to create a search/filtering option in my blood donor application. Where donor can be searched by sex, name, blood group or by selecting all three. Here is my code
Like all the other post you will need to append all the conditions with AND like so. This is the cleanest answer so far. Remember to real escape your strings though use the mysqli OOP way instead of the old mysql. Just a suggestion.
Heres an example of a typical query.
The correct way:
SELECT * FROM donar WHERE name='dxenaretionx' AND sex='M';
The way you are doing it
SELECT * FROM donar WHERE name='dxenaretionx' sex='M';
Code:
function search_donar($_POST) {
$by_name = $_POST['by_name'];
$by_sex = $_POST['by_sex'];
$by_group = $_POST['by_group'];
$by_level = $_POST['by_level'];
//Do real escaping here
$query = "SELECT * FROM donar";
$conditions = array();
if(! empty($by_name)) {
$conditions[] = "name='$by_name'";
}
if(! empty($by_sex)) {
$conditions[] = "sex='$by_sex'";
}
if(! empty($by_group)) {
$conditions[] = "blood_group='$by_group'";
}
if(! empty($by_level)) {
$conditions[] = "e_level='$by_level'";
}
$sql = $query;
if (count($conditions) > 0) {
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$result = mysql_query($sql);
return $result;
}