How to bind an array to the IN() condition in a PDO query?
Hello everyone! I'm new to PHP and PDO, and I've run into a problem. I have an array of user IDs, for example: [1, 5, 7, 12]. I need to select from the users table those whose id is in this array. In regular SQL I would write:
SELECT * FROM users WHERE id IN (1, 5, 7, 12)
But how to do this through PDO with prepared statements? I tried this:
```php
$ids = [1, 5, 7, 12];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id IN (:ids)');
$stmt->execute([':ids' => $ids]);
```
But it doesn't work — PDO complains that it expects a scalar value, not an array. I tried implode and passing it as a string — that's also not an option because it breaks security.
How do I properly bind an array to IN()? Do I need to generate placeholders dynamically? Or is there some tricky way with PDO? I'll be grateful
No answers yet.
Log in to leave an answer