Home >Backend Development >PHP Tutorial >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 (?)
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();
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!