我很好奇是否有可能使用PDO将值数组绑定到占位符。这里的用例试图传递一个值数组,以便与IN()条件一起使用。

我希望能够这样做:

<?php
$ids=array(1,2,3,7,8,9);
$db = new PDO(...);
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN(:an_array)'
);
$stmt->bindParam('an_array',$ids);
$stmt->execute();
?>

并让PDO绑定并引用数组中的所有值。

目前我正在做:

<?php
$ids = array(1,2,3,7,8,9);
$db = new PDO(...);
foreach($ids as &$val)
    $val=$db->quote($val); //iterate through array and quote
$in = implode(',',$ids); //create comma separated list
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN('.$in.')'
);
$stmt->execute();
?>

这当然是工作,但只是想知道是否有一个内置的解决方案,我错过了?


当前回答

使用IN语句有这么重要吗?尝试使用FIND_IN_SET操作。

例如,在PDO中有这样一个查询

SELECT * FROM table WHERE FIND_IN_SET(id, :array)

然后你只需要绑定一个数组的值,用逗号括起来,就像这个

$ids_string = implode(',', $array_of_smth); // WITHOUT WHITESPACES BEFORE AND AFTER THE COMMA
$stmt->bindParam('array', $ids_string);

做完了。

UPD:正如一些人在评论中指出的,有一些问题需要明确说明。

FIND_IN_SET没有在表中使用索引,而且它还没有实现——请参阅MYSQL错误跟踪器中的这条记录。感谢@BillKarwin的通知。 不能使用内部带有逗号的字符串作为数组的搜索值。这是不可能在内爆后以正确的方式解析这样的字符串,因为你使用逗号符号作为分隔符。感谢@VaL的提示。

总之,如果您不严重依赖索引,并且不使用带逗号的字符串进行搜索,那么我的解决方案将比上面列出的解决方案更容易、更简单、更快。

其他回答

以下是我的解决方案:

$total_items = count($array_of_items);
$question_marks = array_fill(0, $total_items, '?');
$sql = 'SELECT * FROM foo WHERE bar IN (' . implode(',', $question_marks ). ')';

$stmt = $dbh->prepare($sql);
$stmt->execute(array_values($array_of_items));

注意array_values的使用。这可以修复键排序问题。

我正在合并id数组,然后删除重复的项。我是这样写的:

$ids = array(0 => 23, 1 => 47, 3 => 17);

那就是失败。

据我所知,没有任何可能将数组绑定到PDO语句中。

但有两种常见的解决方案:

使用位置占位符(?,?,?,?)或命名占位符(:id1,:id2,:id3) 在美元=内爆(',',array_fill (0, count ($ id), ' ? ')); 之前引用数组 $where = array_map(数组($db, 'quote'), $ids);

这两种选择都是好的和安全的。 我更喜欢第二个,因为它更短,如果我需要它,我可以var_dump参数。 使用占位符,您必须绑定值,最终您的SQL代码将是相同的。

$sql = "SELECT * FROM table WHERE id IN ($whereIn)";

最后一个对我来说很重要的是避免错误“绑定变量的数量与标记的数量不匹配”

它是使用位置占位符的一个很好的例子,只是因为它对传入参数有内部控制。

我有一个独特的问题,在将即将被弃用的MySQL驱动程序转换为PDO驱动程序时,我必须创建一个函数,该函数可以动态地从相同的参数数组中构建正常参数和INs。所以我很快就做了这个:

/**
 * mysql::pdo_query('SELECT * FROM TBL_WHOOP WHERE type_of_whoop IN :param AND siz_of_whoop = :size', array(':param' => array(1,2,3), ':size' => 3))
 *
 * @param $query
 * @param $params
 */
function pdo_query($query, $params = array()){

    if(!$query)
        trigger_error('Could not query nothing');

    // Lets get our IN fields first
    $in_fields = array();
    foreach($params as $field => $value){
        if(is_array($value)){
            for($i=0,$size=sizeof($value);$i<$size;$i++)
                $in_array[] = $field.$i;

            $query = str_replace($field, "(".implode(',', $in_array).")", $query); // Lets replace the position in the query string with the full version
            $in_fields[$field] = $value; // Lets add this field to an array for use later
            unset($params[$field]); // Lets unset so we don't bind the param later down the line
        }
    }

    $query_obj = $this->pdo_link->prepare($query);
    $query_obj->setFetchMode(PDO::FETCH_ASSOC);

    // Now lets bind normal params.
    foreach($params as $field => $value) $query_obj->bindValue($field, $value);

    // Now lets bind the IN params
    foreach($in_fields as $field => $value){
        for($i=0,$size=sizeof($value);$i<$size;$i++)
            $query_obj->bindValue($field.$i, $value[$i]); // Both the named param index and this index are based off the array index which has not changed...hopefully
    }

    $query_obj->execute();

    if($query_obj->rowCount() <= 0)
        return null;

    return $query_obj;
}

它仍然未经测试,但逻辑似乎是存在的。

经过一些测试,我发现:

PDO不喜欢’。’(如果你问我的话,我觉得这有点蠢) bindParam是错误函数,bindValue是正确函数。

你可以这样转换:

$stmt = $db->prepare('SELECT * FROM table WHERE id IN('.$in.')');

在此:

$stmt = $db->prepare('SELECT * FROM table WHERE id IN(:id1, :id2, :id3, :id7, :id8, :id9)');

然后用这个数组执行它:

$stmt->execute(array(
        :id1 =>1, :id2 =>2, :id3 =>3, :id7 =>7, :id8 =>8, :id9 => 9
    )
);

因此:

$in = array();
$consultaParam = array();
foreach($ids as $k => $v){
    $in[] = ':id'.$v;
    $consultaParam[':id'.$v] = $v;
}

最后的代码:

$ids = array(1,2,3,7,8,9);
$db = new PDO(...);

$in = array();
$consultaParam = array();
foreach($ids as $k => $v){
    $in[] = ':id'.$v;
    $consultaParam[':id'.$v] = $v;
}

$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN('.$in.')'
);
$stmt->execute($consultaParam);

对我来说,更性感的解决方案是构造一个动态关联数组并使用它

// A dirty array sent by user
$dirtyArray = ['Cecile', 'Gilles', 'Andre', 'Claude'];

// we construct an associative array like this
// [ ':name_0' => 'Cecile', ... , ':name_3' => 'Claude' ]
$params = array_combine(
    array_map(
        // construct param name according to array index
        function ($v) {return ":name_{$v}";},
        // get values of users
        array_keys($dirtyArray)
    ),
    $dirtyArray
);

// construct the query like `.. WHERE name IN ( :name_1, .. , :name_3 )`
$query = "SELECT * FROM user WHERE name IN( " . implode(",", array_keys($params)) . " )";
// here we go
$stmt  = $db->prepare($query);
$stmt->execute($params);