PHP

Build WHERE IN with Placeholders

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Safely interpolate a variable-length list into a "WHERE col IN (...)" clause. Returns the SQL fragment plus the bound parameters — never concatenate user values into SQL.
PHP
Raw
<?php
function whereIn(array $values): array {
    if (!$values) return ['(NULL)', []];   // SQL "IN ()" is a syntax error
    $placeholders = implode(',', array_fill(0, count($values), '?'));
    return ['(' . $placeholders . ')', array_values($values)];
}

[$inSql, $params] = whereIn([5, 12, 19, 22]);
$stmt = $db->prepare("SELECT * FROM users WHERE id IN $inSql");
$stmt->execute($params);
print_r($stmt->fetchAll());
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.