我有这个foreach循环,我用于搜索功能:
$keywords=$_GET['keyword'];
$exploded=explode(' ',trim($keywords));
$mysql_command="SELECT * FROM items WHERE completed='1' AND ";
foreach ($exploded as $key => $value){
if ($key>0)
$mysql_command.=' OR ';
$mysql_command.="title LIKE ? OR description LIKE ?";
}
我想使用这个准备好的声明:
$stmt=$cxn->prepare($mysql_command);
$stmt->execute(array("%$value%","%$value%"));
问题是,我不知道会有多少关键字。那么如何使用未知数量的关键字制作准备好的声明呢?
提前多多感谢。此致
答案 0 :(得分:3)
为什么你不在这样的请求之后创建数组:
$params=Array();
foreach($exploded as $key => $value){
$params[]="%$value%";
}
$stmt->execute($params);
答案 1 :(得分:0)
mysqli不允许直接使用数组调用execute
或bind_param
。您必须使用call_user_func_array
,如下所示:
call_user_func_array(array($stmt, "bind_param"), array("s", "%test%"));
然后,要构建数组,您可以使用:
class BindParam{
private $v = array("");
public function add( $type, &$value ){
$this->v[0] .= $type;
$this->v[] = &$value;
}
public function get(){
return $this->v;
}
}
这是http://php.net/manual/en/mysqli-stmt.bind-param.php#109256的调整版本。然后像这样使用它:
$searchTerms = explode(' ', $filter);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "title LIKE ?";
$a = '%'.$term.'%';
$bindParam->add('s', $a); // can't pass by value
}
}
$filter_sql = "WHERE " . implode(' AND ', $searchTermBits);
/*...*/
call_user_func_array(array($stmt, "bind_param"), $bindParam->get());