我有一个带分页的搜索/过滤器表单,所以我必须使用$ _GET来获取url中的参数。现在我想用也准备好的声明更安全。
问题是,如果我留下一个空字段,我会收到错误。有没有办法绕过这个问题? 我搜索了这个wbsite,我发现研讨会问题,但他们都是关于将空字段插入数据库。
$input = $_GET['input'];
$categories = $_GET['category'];
$state = $_GET['state'];
$zipcode = $_GET['zipcode'];
$targetpage = "send.php";
$limit = 3;
//This query checks for data
$qq = " SELECT * FROM classified where confirm='0' ";
if (!empty($input)) {
$qq .= "AND title LIKE :input ";
}
if (!empty($categories) ){
$qq .= "AND id_cat = :categories ";
}
if (!empty($state) ) {
$qq .= "AND id_state = :state ";
}
if (!empty($zipcode) ) {
$qq .= "AND zipcode = :zipcode ";
}
$qq .= "ORDER BY date DESC ";
$qq = $db->prepare($qq);
$input = "%".$input."%";
// Bind the parameter
$qq->execute(array(':input'=> $input,
':categories'=> $categories,
':state'=> $state,
':zipcode'=> $zipcode ));
我得到的错误是
PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
in ....send.php on line 56
是':zipcode'=> $ zipcode));
答案 0 :(得分:2)
在构建查询时构建要绑定的数组
$to_bind = array();
if (!empty($input)) {
$qq .= "AND title LIKE :input ";
$to_bind[':input'] = $input;
}
if (!empty($categories) ){
$qq .= "AND id_cat = :categories ";
$to_bind[':categories'] = $categories ;
}
if (!empty($state) ) {
$qq .= "AND id_state = :state ";
$to_bind[':state'] = $state ;
}
if (!empty($zipcode) ) {
$qq .= "AND zipcode = :zipcode ";
$to_bind[':zipcode'] = $zipcode ;
}
...
$qq->execute($to_bind);
我不确定传递一个空数组是否会导致问题,因为所有参数都是空的。
答案 1 :(得分:-1)
尽量不要重复自己。想象一下,如果搜索过滤器中有50个字段。
$input = $_GET['input'];
$categories = $_GET['category'];
$state = $_GET['state'];
$zipcode = $_GET['zipcode'];
$targetpage = "send.php";
$limit = 3;
$Param = array();
//This query checks for data
$qq = " SELECT * FROM classified where confirm='0' ";
if (!empty($input)) {
$qq .= "AND title LIKE :input ";
$Param[':input'] = $input;
}
if (!empty($categories) ){
$qq .= "AND id_cat = :categories ";
$Param[':categories'] = $categories ;
}
if (!empty($state) ) {
$qq .= "AND id_state = :state ";
$Param[':state'] = $state ;
}
if (!empty($zipcode) ) {
$qq .= "AND zipcode = :zipcode ";
$Param[':zipcode'] = $zipcode ;
}
$qq .= "ORDER BY date DESC ";
$qq = $db->prepare($qq);
$qq->execute($Param);
我希望这会有所帮助