Passing an array to a query using a WHERE clause
To pass an array to a WHERE clause in PHP, you can use the implode
function to join the array elements with a comma separator and use them in your WHERE clause. Here is an example:
<?php
$ids = [1, 2, 3, 4, 5];
// Join the array elements with a comma separator
$ids_str = implode(',', $ids);
// Use the IN operator in your WHERE clause
$query = "SELECT * FROM table WHERE id IN ($ids_str)";
Watch a video course
Learn object oriented PHP
You can also use PDO
and bind the array elements as parameters to prevent SQL injection attacks:
<?php
$ids = [1, 2, 3, 4, 5];
// Create a placeholders string
$placeholders = implode(',', array_fill(0, count($ids), '?'));
// Bind the array elements as parameters
$stmt = $pdo->prepare("SELECT * FROM table WHERE id IN ($placeholders)");
$stmt->execute($ids);