2011-10-10 119 views
0

我正在为演员经理编制演员并能够浏览他们的平台。我的表'演员'设置与名字,姓氏,电子邮件,电话,地址等。简化mysql筛选器查询

我有一个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; 
} 

简化这个或建议的任何帮助?

回答

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语句中使用位置参数。

+0

这很好。我在WHERE字段LIKE'&'的原因是因为我找不到一种方法来编译SQL字符串足够聪明,知道在哪里插入“AND”和“WHERE”。这给了我更多的选择,更少的代码和我现在知道的内爆函数将会有所帮助。谢谢! – wwwroth

+0

记得清理您的数据输入 – Daniel

0

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

另外,您的查询容易受到SQL injections的影响。

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

+1

正如我上面发布的,我不得不运行LIKE'%',因为我无法弄清楚如何以及在哪里插入'AND'并保持正确的SQL语法。感谢SQL注入的提示,这也只是在DEV阶段,所以稍后我会通过并保护到数据库的输入。 – wwwroth

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"; 
} 
+0

请记住清理您的用户输入! – Daniel