Php:带CASE和多选的sql查询

时间:2017-07-10 12:55:12

标签: php sql

我正在尝试根据用户的搜索条件查询数据库,其中一个标准是注册的性别:男性或女性。

但是,用户可以作为条件发送male femaleanything。我试图在用户发送anything时选择所有行,但是我的结果是空的。

以下是我的一些试验,但似乎都没有效果,但它适用于male female

的案例
$query = "SELECT * 
            FROM UsersInfo 
            WHERE gender = CASE '$et_gender'
                WHEN 'male' THEN 'male'
                WHEN 'female' THEN 'female'
                WHEN 'anything' THEN 'female' AND 'male'
                            END";


$query = "SELECT * 
            FROM UsersInfo 
            WHERE gender = CASE '$et_gender'
                WHEN 'male' THEN 'male'
                WHEN 'female' THEN 'female'
                WHEN 'anything' THEN SELECT * FROM UsersInfo
                            END";


$query = "SELECT * 
                FROM UsersInfo 
                WHERE gender = CASE '$et_gender'
                    WHEN 'male' THEN 'male'
                    WHEN 'female' THEN 'female'
                    WHEN 'anything' THEN * 
                                END";

2 个答案:

答案 0 :(得分:1)

我看到的是,您根本不需要提及任何过滤条件,您的查询可能只是

SELECT * FROM UsersInfo 

(OR)使用IN运算符,如

WHERE gender IN ('male','female','anything')
每个发布的代码的

(OR)使用等于运算符=

WHERE gender = '$et_gender'

答案 1 :(得分:1)

你可以尝试:

 $query =   "SELECT * 
    FROM UsersInfo 
    WHERE (gender = '$et_gender' AND '$et_gender' IN ('male', 'female')) OR ('$et_gender'='anything')"

根据值,我想你也可以缩写它(但要做一些检查):

  $query =   "SELECT * 
        FROM UsersInfo 
        WHERE (gender = '$et_gender') OR ('$et_gender'='anything')"