一尘不染

准备好的语句“ WHERE .. IN(..)”查询和排序-使用MySQL

mysql

假设我们有一个查询:

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();
    }

但是现在我必须手动对结果进行排序。我有其他不错的选择吗?


阅读 242

收藏
2020-05-17

共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完成排序。

2020-05-17