PHP / MySQLi - array as bind_param

251 Views Asked by At

I am curious if there is a way to bind array of parameters at once?

In simple words, something like this:

$sql = "SELECT * FROM table WHERE id IN (?)";
$stmt = $db->prepare($sql);
$stmt->bind_param("<array>", $array_of_ids);
$stmt->execute();

Thoughts?

2

There are 2 best solutions below

0
On

I don't think you can do that as such but if you set up an array of params and values you could use a foreach loop something like

$params=array(
    ':id'=>1,
    ':cat'=>'bananas'
    ':type'=>100
);
foreach( $params as $param=>$value )$stmt->bind_param( $param,$value );
0
On

Since PHP 5.6, this is possible with the ... operator (see also the documentation). This operator unpacks a list when calling a function, causing the list to act like multiple variables.

You could use the following:

$stmt->bind_param($types, ...$data);

This assumes that $types is a string containing the types for the data and $data a list containg the data for the query.