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


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

我需要运行下面的查询。它问我很多麻烦。事实上,我有几个"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()一次,一个数组包含你需要绑定的所有参数,所以你的解决方案是只将额外的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
}