duankange2433 2015-09-22 07:09
浏览 32
已采纳

动态构建SQL搜索查询?

I am trying to build a search query based on the input from users, but I am having problems with the AND and WHERE keywords. Here is the code:

if (isset($_POST['submitBtn'])) {

    $gender = $_POST['gender'];
    $level = $_POST['level'];
    $status = $_POST['status'];

    $query = 'SELECT * FROM candidate ';
    $where = array();

    $criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
    foreach ($criteria as $key => $value) {
        if ($value !== 'all') {
            $where[] = $key . ' = ' . $value;
        }
    }

}

The output looks like this:

Array
(
    [0] => gender = masculine
    [1] => level = low
    [2] => status = future
)

If no option is selected, it defaults to 'all' and it is excluded from the $where[].

I need to achieve this, or anything similar:

Array
(
    [0] => WHERE gender = masculine
    [1] => AND level = low
    [2] => AND status = future
)

The WHERE must be appended only if one or more options have been selected and the AND must be appended only if two or more options have been selected.

In the code I am using I have 9 search inputs. To keep it clear I only displayed three in the snippet. Can you please help me figure this out?

  • 写回答

4条回答 默认 最新

  • duanliaolan6178 2015-09-22 07:18
    关注

    Try this:I think you need the whereClause in string not in array,here you can choose any one from two and remove the other one.

    <?php 
    $where=array();$flag=0;// use flag to identify the where/and
     $whereClause="";
     $criteria = array('gender' => "masculine", 'level' => "low", 'status' => "future");
        foreach ($criteria as $key => $value) {
            if ($value !== 'all') {
                if($flag == 0){
                 $where[] = " WHERE " .$key . ' = ' . $value;//if you need array
                 $whereClause='WHERE '.$key . ' = "' . $value.'"';//if you need string
                }else{
                 $where[] = " AND " .$key . ' = ' . $value;
                 $whereClause .=' AND '.$key . ' = "' . $value.'"';
                }
                 $flag++;
            }
        }
        echo "<pre>";
        print_r($where);
        echo "</pre>";
    
       echo $whereClause;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端