我有一个表(mysql),它包含五个列(id,people,gender, age and years),每个列包含不同的值,如下所示,
id | people | gender | age | year |
1 | Mark | M | 10 | 2010 |
2 | luke | F | 20 | 2014 |对于这些数据,我希望根据指定的条件从表中进行一些查询。以下是条件
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.我使用php脚本从mysql表调用数据。您可以看到调用数据的许多指定条件,当从表单中选择条件时,我希望能够从一个脚本执行它们。问题是使用许多if and else conditions来执行它们,我想知道是否还有另一个选项来阻止指定多个if and else conditions来执行上面的条件。谢谢你的帮助。
发布于 2014-06-19 14:33:05
也许你可以这样做:
$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;如果您的$selection包含更多的内容,例如年龄和性别,结果将是:
'age = %d and gender = %s'https://stackoverflow.com/questions/24309010
复制相似问题