Skip to content

Instantly share code, notes, and snippets.

@terrymun
Last active August 29, 2015 14:27
Show Gist options
  • Save terrymun/bdde81168adf13f40864 to your computer and use it in GitHub Desktop.
Save terrymun/bdde81168adf13f40864 to your computer and use it in GitHub Desktop.
Filling placeholders in the IN clause
<?php
// Assuming that database connection is already open
// Get username
$userIDs = array(10, 38, 56, 93);
// Method 1: array_fill() then implode()
$placeholders = implode(',', array_fill(0, count($userIDs), '?'));
// Method 2: str_repeat() then str_split() then implode()
$placeholders = implode(',', str_split(str_repeat('?', count($userIDs))));
// Method 3: str_repeat() then substr()
$placeholders = substr(str_repeat('?,', count($userIDs)), 0, -1);
// Method 4: str_repeat() then append last placeholder
$placeholders = str_repeat('?,', count($userIDs)-1).'?';
// Prepare and execute statement
$stmt = $db->prepare("SELECT user, email, country FROM users WHERE id IN ($placeholders)");
$stmt->execute($userIDs);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment