I have a users page, where all the users in the system are displayed by default.
I am trying to apply filters so that users can refine their search for a user. For example, view all users who are male.
By default, to display all users on users.php
, I am running this query by default:
$get_all_users = "SELECT * FROM users";
But when a user for example selected they want to view all female users on the system, then I want to run this query (example):
$get_all_users = "SELECT * FROM users WHERE gender = 'female'";
But for some reason, the query which displays all users by default, is always being executed. Here is my approach:
// get gender from radio buttons
$refined_gender = htmlentities (strip_tags(@$_POST['gender']));
$get_all_users = "SELECT * FROM users";
if (isset($_POST['submit'])){
if (isset($_POST['gender'])) {
if ($refined_gender){
$get_all_users = "SELECT * FROM users WHERE gender = '$refined_gender'";
}
}
}
Like I would build the WHERE clause (something like that atleast) Not tested
$get_all_users = "SELECT * FROM users" . buildWhereClause($_POST);
function buildWhereClause($_POST) {
$where = 'WHERE 1=1';
foreach($_POST as $k => $v) {
//check if $v is valid with a different function
switch($k) {
case 'gender':
$where .= sprintf('AND `gender` = `%s`', $v);
break;
case 'age':
$where .= sprintf('AND `age` = %d', $v);
break;
}
}
return $where;
}
This is a very lame function and should not be used as is. Just as an example where it could lead to. I'm sure theres clever ways of doing it and you dont always want an AND
.