首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止php和mysql中的许多if和else条件

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

Stack Overflow用户
提问于 2014-06-19 14:25:52
回答 1查看 105关注 0票数 0

我有一个表(mysql),它包含五个列(id,people,gender, age and years),每个列包含不同的值,如下所示,

代码语言:javascript
复制
id | people | gender | age | year |
 1 |  Mark  | M      | 10  | 2010 |
 2 |  luke  | F      | 20  | 2014 |

对于这些数据,我希望根据指定的条件从表中进行一些查询。以下是条件

代码语言:javascript
复制
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来执行上面的条件。谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-19 14:33:05

也许你可以这样做:

代码语言:javascript
复制
$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包含更多的内容,例如年龄和性别,结果将是:

代码语言:javascript
复制
'age = %d and gender = %s'
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24309010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档