2

我有这个 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%"));

问题是,我不知道会有多少关键字。那么如何使用未知数量的关键字制作准备好的语句?

提前非常感谢。问候

4

2 回答 2

3

为什么在这样的请求之后不创建数组:

$params=Array();
foreach($exploded as $key => $value){
  $params[]="%$value%";
}
$stmt->execute($params);
于 2012-05-19T12:19:42.887 回答
0

mysqli 不允许直接调用executebind_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());
于 2014-02-05T00:30:44.313 回答