Reputation: 1114
I have a table (mysql) which contains five columns (id,people,gender, age and years)
, each column contains different values which is listed below,
id | people | gender | age | year |
1 | Mark | M | 10 | 2010 |
2 | luke | F | 20 | 2014 |
With this data I want to make some queries from the table depending on a specified condition. Below are the conditions
I want to
1. select all people from the table.
2. select people from the where gender is M.
3. select people from the table where gender is M and Year is 2010.
4. select people from the table where age is 10 and gender is M and year is 2010
5. select people from the table where age is 20.
6. select people from the table where year is 2014.
7. select people from the table where year is 2010 and age is 10.
I am using php script to call data from mysql table.
You see this many specified conditions calling the data, I want to be able to execute them from one script when the condition is selected from a form. The problem is using many if and else conditions
to execute them, I want to know if there is another option to prevent specifying many if and else conditions
to execute the conditions above.
Thanks for helping.
Upvotes: 0
Views: 108
Reputation: 2200
maybe you can do something like this:
$query = "SELECT
id,
people,
gender,
age,
years
FROM
table
";
$clause = array();
if(isset($selection['age'])) $clause[] = 'age = %d';
if(isset($selection['gender'])) $clause[] = 'gender = %s';
if(isset($selection['year'])) $clause[] = 'year = %d';
$whereclause = implode(' and ', $clause);
if(count($clause) > 0) $query .= 'WHERE '.$whereclause;
if your $selection contains more the one, e.g. age and gender the result would be:
'age = %d and gender = %s'
Upvotes: 3