Consider the following query that retrieves rows based on specific IDs:
SELECT * FROM somewhere WHERE `id` IN(1,5,18,25) ORDER BY `name`;
Given an array of IDs ($ids) to fetch, it's recommended to use prepared statements for efficiency. However, using a loop to iterate over the array and bind each ID separately requires subsequent manual sorting of results.
To simplify this process and maintain MySQL ordering, an alternative approach exists:
$ids = array(1,5,18,25); // Construct a placeholder string containing ?,?,? etc. $clause = implode(',', array_fill(0, count($ids), '?')); $stmt = $mysqli->prepare('SELECT * FROM somewhere WHERE `id` IN (' . $clause . ') ORDER BY `name`;'); // Bind all IDs to the placeholder string using call_user_func_array call_user_func_array(array($stmt, 'bind_param'), $ids); $stmt->execute(); // Iterate over the results
This method binds all IDs to the placeholder string in one call, allowing MySQL to perform the filtering and sorting efficiently.
The above is the detailed content of How Can I Efficiently Use Prepared Statements with Array Filters in MySQL's `WHERE ... IN()` Clause?. For more information, please follow other related articles on the PHP Chinese website!