Home > Backend Development > PHP Tutorial > How to Query MySQL with an Array in the WHERE Clause?

How to Query MySQL with an Array in the WHERE Clause?

Patricia Arquette
Release: 2024-12-25 13:42:09
Original
352 people have browsed it

How to Query MySQL with an Array in the WHERE Clause?

Querying MySQL with an Array using a WHERE Clause

To construct a query string that uses an array of values in a WHERE clause, consider the following approach:

SELECT *
FROM galleries
WHERE id IN (?)
Copy after login

Here's how to create and execute this query using PHP and MySQLi:

$galleries = array(1, 2, 5);
$id_list = implode(',', array_fill(0, count($galleries), '?'));

$stmt = $conn->prepare("SELECT * FROM galleries WHERE id IN ({$id_list})");
$stmt->bind_param(str_repeat('i', count($galleries)), ...$galleries);
$stmt->execute();
Copy after login

This query will return all rows from the galleries table where the id field matches any of the values in the $galleries array.

The above is the detailed content of How to Query MySQL with an Array in the WHERE Clause?. For more information, please follow other related articles on the PHP Chinese website!

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