假设我们有一个查询:
SELECT * FROM somewhere WHERE `id` IN(1,5,18,25) ORDER BY `name`;
以及要获取的ID数组: $ids = array(1,5,18,25)
$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(); }
但是现在我必须手动对结果进行排序。我有其他不错的选择吗?
您可以这样进行:
$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完成排序。