如何在php中动态添加多个WHERE子句

时间:2015-05-23 12:48:02

标签: php mysql

我有五个输入字段,即技能,位置,公司,经验和薪水。根据用户要求,我将从数据库中获取值。我的问题是,如何动态地使用where条件?考虑用户在技能和公司输入字段中输入值,我想从数据库中获取这些值如何做到这一点?现在我保持20条,如果有条件解决这个问题

public function get_jobonline($skillname,$userid,$location)
{
    $company=$this->input->post('searchcompany');
    $experience=$this->input->post('experience');
    $salary=$this->input->post('salary');
    echo $company;
    if($location==NULL)
    {
        $query=$this->db->query("SELECT j.id AS job_id, j.created_date,j.title, l.city AS location, cm.name AS company_name,
        cm.logo FROM  `jobs` AS j
        LEFT JOIN  `keyword` AS k ON  `k`.`job_id` =  `j`.`id` 
        LEFT JOIN  `keyword_master` AS km ON  `km`.`id` =  `k`.`keyword_id` 
        LEFT JOIN  `location_master` AS l ON  `l`.`id` =  `j`.`location` 
        LEFT JOIN  `company_master` AS cm ON  `cm`.`id` =  `j`.`company_id` 
        WHERE km.name = '$skillname' AND j.uid='$userid'
        ;");
    }
    else
    {
        $query=$this->db->query("SELECT j.id AS job_id, j.created_date,j.title, l.city AS location, cm.name AS company_name,
        cm.logo FROM  `jobs` AS j
        LEFT JOIN  `keyword` AS k ON  `k`.`job_id` =  `j`.`id` 
        LEFT JOIN  `keyword_master` AS km ON  `km`.`id` =  `k`.`keyword_id` 
        LEFT JOIN  `location_master` AS l ON  `l`.`id` =  `j`.`location` 
        LEFT JOIN  `company_master` AS cm ON  `cm`.`id` =  `j`.`company_id` 
        WHERE km.name = '$skillname' AND j.uid='$userid' AND l.city='$location'
        ;");
    }

    // if($company != NULL && )

    return $query->result_array();
}

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望根据用户输入动态更改查询。 为此,您应该将查询本身与查询函数分开。

伪代码中的Ex:

// Let's suppose it's your base query 
// (that meets the minimum field required to do the research).
$sql = "SELECT j.id AS job_id, j.created_date,j.title,... WHERE 
         km.name = '$skillname'";

// U add the condition skill if the user typed it
if(isset($_POST['skill'])
    $sql .= "AND j.skill = '$_POST['skill']'";

... (for every input filled u add condition to the query)

// WHEN all input u needed to add are tested
// Query the DB
$query = $this->db->query($sql);

U甚至可以通过包含所有输入名称字段的数组来实现更好的效果,以便循环到它上面。

答案 1 :(得分:1)

查询是字符串(几乎可以读取)。您可以使用字符串处理创建它们。如果您查看由此类软件生成的查询,您会发现他们经常阅读

 WHERE 1=1 AND name='value' and address = 'street' and job = 'driver'

等。 WHERE 1=1部分是用于生成查询的代码如下所示:

$q = "SELECT something JOIN something ON something...WHERE 1=1 ";
if (isset($val1))  $q .= " AND name= '$val1'";
if (isset($val2))  $q .= " AND street = '$val2'";
if (isset($val3))  $q .= " AND job = '$val3'";

if(!($result = db->query($q)) {
      /* error */
} else {
      /* process the resultset */
}

即使没有搜索条件,WHERE 1=1也是确保查询有效的黑客攻击:即使if个语句都不成立,也是如此。它有点难看,但SQL理解它并且不会使查询花费更多时间。

如您所见,此策略会在查询中添加可变数量的AND子句,具体取决于用户提供的查询参数。

这个例子只有一个问题。它没有使用绑定变量,所以它对SQL注入开放。通过在一系列AND column=?语句中构建一系列绑定变量以及一系列if子句,可以解决这个问题。