Home > Backend Development > PHP Tutorial > How Can I Efficiently Use Prepared Statements with Array Filters in MySQL's `WHERE ... IN()` Clause?

How Can I Efficiently Use Prepared Statements with Array Filters in MySQL's `WHERE ... IN()` Clause?

Mary-Kate Olsen
Release: 2024-12-16 16:33:11
Original
758 people have browsed it

How Can I Efficiently Use Prepared Statements with Array Filters in MySQL's `WHERE ... IN()` Clause?

Prepared Statement with Array Filter: 'WHERE .. IN(..)' Query

Problem

Consider the following query that retrieves rows based on specific IDs:

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

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.

Solution

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template