How to pass an array to a query using a WHERE clause with PHP?

Spread the love

Sometimes, we want to pass an array to a query using a WHERE clause with PHP.

In this article, we’ll look at how to pass an array to a query using a WHERE clause with PHP.

How to pass an array to a query using a WHERE clause with PHP?

To pass an array to a query using a WHERE clause with PHP, we create a string with the values in between the parentheses and interpolate them into the SQL string.

For instance, we write

$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
    SELECT *
    FROM galleries
    WHERE id IN ($in);
SQL;
$statement = $mysqli->prepare($select);
$statement->bind_param(str_repeat('i', count($ids)), ...$ids);
$statement->execute();
$result = $statement->get_result();

to create an array with the values with array_fill(0, count($ids), '?').

Then we join them with ', ' and assign the combined string to $in.

Then we add the placeholders into the $seelct string.

Then we call bind_params with 'i' repeated for the number of times equal to the count of $ids and the values in $ids.

Then we call execute to run the statement and call get_result to get the returned results.

Conclusion

To pass an array to a query using a WHERE clause with PHP, we create a string with the values in between the parentheses and interpolate them into the SQL string.

Leave a Reply

Your email address will not be published.