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

时间:2015-01-18 16:49:34

标签: php mysql mysqli

我需要运行下面的查询。它问了我很多麻烦。事实上,我有几个" 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

}

1 个答案:

答案 0 :(得分:2)

重要的是,您只需调用一次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
}