防止php和mysql中的许多if和else条件

时间:2014-06-19 14:25:53

标签: php mysql sql

我有一个表(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来执行上述条件。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

也许你可以这样做:

$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;

如果你的$选择包含更多的那个,例如年龄和性别的结果将是:

'age = %d and gender = %s'