How to use "WHERE IN" in MYSQLi Prepared Statements in PHP?
<?php
$ids = [1,2,3,4,5]; // any array of ids
$count = count($id);
$placeholders = implode(',', array_fill(0, $count, '?'));
$bindStr = str_repeat('i', $count);
$stmt = $mysqli -> prepare("SELECT * FROM table WHERE id IN ($placeholders)");
$stmt -> bind_param($bindStr, ...$ids);
$stmt -> execute();
-
First, assume that we have an array of ids
-
$count saves the length of that array
-
We save the MYSQL placeholders ?,?,? in $placeholders
-
array_fill() creates an array from indexes 0 to $count and fills it with ?
-
implode() joins array elements with commas ,
-
As all the ids are integers, we will create the first parameter for bind_param() function ($bindStr) using the str_repeat() function.
-
Then we prepare the statement.
-
In bind_param() method, we use ... (Splat operator) to send each array element as a parameter.
-
Finally, we execute the query.
Tagged:
PHP
MYSQLi