在 mysqli 预准备语句中使用数组:“WHERE ..IN(..)' 查询

2022-08-30 14:52:49

想象一下,我们有一个查询:

SELECT * FROM somewhere WHERE `id` IN(1,5,18,25) ORDER BY `name`;

和要获取的 ID 数组:$ids = array(1,5,18,25)

对于预准备的语句,建议准备一个语句并多次调用它:

$stmt = $mysqli->prepare('SELECT * FROM somewhere WHERE `id`=?;');
foreach ($ids as $id){
    $stmt->bind_params('i', $id);
    $stmt->exec();
}

但现在我必须手动对结果进行排序。我有什么好的选择吗?


答案 1

你可以这样做:

$ids = array(1,5,18,25);

// creates a string containing ?,?,? 
$clause = implode(',', array_fill(0, count($ids), '?'));


$stmt = $mysqli->prepare('SELECT * FROM somewhere WHERE `id` IN (' . $clause . ') ORDER BY `name`;');

call_user_func_array(array($stmt, 'bind_param'), $ids);
$stmt->execute();

// loop through results

使用这个,你为每个id调用bind_param,并且你已经通过mysql完成了排序。


答案 2

有同样的问题,除了7年前@sled的答案外,这里有一种可能性,无需迈出这一步,而只能拨打bind_params一次:call_user_func_array(array($stmt, 'bind_param'), $ids);

$ids = array(1,5,18,25);

// creates a string containing ?,?,? 
$bindClause = implode(',', array_fill(0, count($ids), '?'));
//create a string for the bind param just containing the right amount of s 
$bindString = str_repeat('s', count($ids));

$stmt = $mysqli->prepare('SELECT * FROM somewhere WHERE `id` IN (' . $bindClause . ') ORDER BY `name`;');

$stmt->bind_param($bindString, ...$ids);
$stmt->execute();

推荐