简化mysql过滤器查询

时间:2011-10-10 00:17:47

标签: php mysql wildcard sql-like

我正在为演员经理建立一个平台,以便对Actors进行编目并能够浏览它们。我的桌子'演员'设置了名字,姓氏,电子邮件,电话,地址等。

我有一个browse.php页面,其中包含一个用于过滤结果的表单。这是我的课程,我需要帮助简化以及当字段为空时摆脱通配符结果。

我将表单数据传递给数组$ search,并且类检查数组部分是否已填充并写入SQL查询。

public function getActors($search) {
    if(isset($search)) {
        if($search["first_name"] == NULL) { $first_name = "LIKE '%'"; } else { $first_name = "LIKE '".$search["first_name"]."'"; }
        if($search["last_name"] == NULL) { $last_name = "LIKE '%'"; } else { $last_name = "LIKE '".$search["last_name"]."'"; }
        if($search["gender"] == NULL) { $gender = "LIKE '%'"; } else { $gender = " = '".$search["gender"]."'"; }
        if($search["address_state"] == NULL) { $address_state = "LIKE '%'"; } else { $address_state = " = '".$search["address_state"]."'"; }
        if($search["ethnicity"] == NULL) { $ethnicity = "LIKE '%'"; } else { $ethnicity = " = '".$search["ethnicity"]."'"; }
        if($search["status"] == NULL) { $status = "LIKE '%'"; } else { $status = " = '".$search["status"]."'"; }

        $sql = "SELECT * FROM actor WHERE
            first_name ".$first_name." AND
            last_name ".$last_name." AND
            gender ".$gender." AND
            address_state ".$address_state." AND
            ethnicity ".$ethnicity." AND
            status ".$status."
        ";          
    } else {
        $sql = "SELECT * FROM actor";   
    }
    $s = mysql_query($sql) or die (mysql_error());
    $numrows = mysql_num_rows($s);

    for($x=0; $x < $numrows; $x++){
        $actorArray[$x] = mysql_fetch_row($s);
    }
    return $actorArray;
}   

有关简化此建议或建议的任何帮助吗?

3 个答案:

答案 0 :(得分:1)

对于条件,我可以使用foreach循环。

 if(isset($search)) {
        $conditions = array();
        foreach($search as $k => $criteria){
            if ($criteria != NULL){
                $condition[] = "{$k} LIKE '{$criteria}'";
                //this will produce for $search['first_name'] = 'john'
                //  "first_name LIKE 'john'"
            }
        }
        //we transform the array of conditions into a string
        $conditions = implode (' AND ', $conditions);
        $sql = "SELECT * FROM actor WHERE " . $conditions;

 }else{
        $sql = "SELECT * FROM actor";   
 }

答案 1 :(得分:0)

LIKE '%'?当真?为什么不只是包含特定条款,如果它是null?

此外,您的查询容易受到SQL injections的攻击。<​​/ p>

在阅读了SQL注入之后,您可以通过遍历$ search数组,添加特定子句并绑定参数来添加WHERE子句。

答案 2 :(得分:0)

isset区内)......

$fields = array('first_name','last_name','gender','address_state','ethnicity','status');
$parts = array();
foreach($fields as $field) {
  if(!empty($search[$field])) {
    $parts[] = $field . ' LIKE "' . $search[$field] . '"';
  }
}
$sql = "SELECT * FROM actor WHERE " . implode(' AND ', $parts);

正如@Dvir所提到的,最好在SQL语句中使用位置参数。