Last active
August 29, 2015 14:27
-
-
Save terrymun/bdde81168adf13f40864 to your computer and use it in GitHub Desktop.
Filling placeholders in the IN clause
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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