This question already has an answer here:
I have an array in PHP which may contain data such as this:
$data = array("Apples", "Oranges", "Grapes", "Pears");
I then want to pass these values into the mysqli
bind_param
function. For this example it would look like this:
$stmt->bind_param("ssss", $data[0], $data[1], $data[2], $data[3]);
My question is how can I produce the same results as above if the length of the array is unknown? For example it may be five, ten or 15 elements long.
</div>
With PHP 5.6 or higher:
$stmt->bind_param(str_repeat("s", count($data)), ...$data);
With PHP 5.5 or lower you might (and I did) expect the following to work:
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $data));
...but mysqli_stmt::bind_param
expects its parameters to be references whereas this passes a list of values (thanks Barmar for pointing this out).
You can work around this (although it's an ugly workaround) by first creating an array of references to the original array.
$references_to_data = array();
foreach ($data as &$reference) { $references_to_data[] = &$reference; }
unset($reference);
call_user_func_array(
array($stmt, "bind_param"),
array_merge(array(str_repeat("s", count($data))), $references_to_data));