Mysqli 准备语句:几个 WHERE 子句和 WHERE IN(数组)

Mysqli prepared statement : several WHERE clauses and WHERE IN (Array)

我需要运行下面的查询。这给我带来了很多麻烦。事实上,我有几个"WHERE"条件,一个需要分解一个数组。

This issue 帮助了我,但它没有几个条件 "WHERE" .

$array = (1,2,3,4,5,6,7,8,9,10);

$clause = implode(',', array_fill(0, count($array), '?'));

if($request = $this->getConnexion()->prepare('SELECT col1, col2 FROM table WHERE col1 IN ('.$clause.') AND col2>=?') or die(mysqli_error($this->getConnexion()))) {

    // The problem starts here
    call_user_func_array(array($request, 'bind_param'), $array);

    $request->bind_param('i', $this->getTime());
    // Until here

    $request->execute();
    $request->bind_result($col1, $col2);
    $request->store_result();

    // Following the code

}

这里重要的是你只调用 bind_param() 一次,数组包含你需要绑定的 all 参数,所以你的解决方案将只是将附加的 WHERE 子句参数添加到要绑定的 $array 值中。 IN() 子句不是需要将 call_user_func_array() 与其他参数分开的特殊情况。你在 所有 个中调用它。

虽然缺少一些东西 - bind_param() 的第一个参数是一个数据类型的字符串。您所有的类型都是 i,因此您需要使用 str_repeat() 来创建它。

// Eventually, this array will contain the other params too
$array = (1,2,3,4,5,6,7,8,9,10);

// This creates a string of ?,?,?,?... for the IN () clause    
$clause = implode(',', array_fill(0, count($array), '?'));

// Add the additional value onto the $array array
// so the last param is bound with the others.
$array[] = $this->getTime();

$types = str_repeat('i', count($array));

// The params passed to call_user_func_array() must have as references, each subsequent value. Add those in a loop, but start with the $types string
$params = array($types);
foreach ($array as $key => $value) {
   $params[] = &$array[$key];
}

if($request = $this->getConnexion()->prepare('SELECT col1, col2 FROM table WHERE col1 IN ('.$clause.') AND col2>=?') or die(mysqli_error($this->getConnexion()))) {

    // Then bind_param() is called on all parameters
    // using the $params array which includes types and param references
    call_user_func_array(array($request, 'bind_param'), $params);

    // Execute & fetch.
    $request->execute();
    $request->bind_result($col1, $col2);
    $request->store_result();

    // Following the code
}