我有这个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%"));
问题是,我不知道会有多少个关键字。那么,我怎样才能使用未知数量的关键字制作准备好的语句呢?
提前非常感谢。问候
为什么在请求后不像这样创建数组:
$params=Array();
foreach($exploded as $key => $value){
$params[]="%$value%";
}
$stmt->execute($params);
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());