我有这个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%"));问题是,我不知道会有多少关键词。那么,如何使用未知数量的关键字创建预准备语句呢?
在此之前非常感谢。问候
发布于 2012-05-19 20:19:43
为什么不在请求后创建数组,如下所示:
$params=Array();
foreach($exploded as $key => $value){
$params[]="%$value%";
}
$stmt->execute($params);发布于 2014-02-05 08:30:44
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());https://stackoverflow.com/questions/10665047
复制相似问题