0

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.

Kian Cross
  • 1,818
  • 2
  • 21
  • 41

1 Answers1

5

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));
Matt Raines
  • 4,149
  • 8
  • 31
  • 34
  • wow, I like your php<=5.5 answer, you need to add it to [this question](http://stackoverflow.com/q/5100046/4233593) – Jeff Puckett Jun 10 '16 at 22:45
  • @JeffPuckettII I'm not sure I understand that question. It's a bit late in the day :) – Matt Raines Jun 10 '16 at 22:47
  • This is a duplicate question, and your answer is better than the originals, so I suggest you add it there also for future readers. – Jeff Puckett Jun 10 '16 at 22:48
  • I don't think this works because `bind_param` takes reference arguments. – Barmar Jun 10 '16 at 23:12
  • That's why the answer in the other question is more complicated – Barmar Jun 10 '16 at 23:13
  • Interesting @Barmar, I didn't consider that. The [documentation for mysqli_stmt::bind_param](http://php.net/manual/en/mysqli-stmt.bind-param.php) suggests you might be right. I'll see what happens when I test it. – Matt Raines Jun 10 '16 at 23:15
  • @Barmar is correct, this doesn't work. I've added an ugly workaround which fixes it. – Matt Raines Jun 10 '16 at 23:28
  • There's another question with a very complete answer, why are you bothering? – Barmar Jun 10 '16 at 23:28
  • 1
    This question is much more specific than the other question, the reading of which (let alone the answers there) makes my nose bleed. I didn't think it was a duplicate, but you live and learn... – Matt Raines Jun 10 '16 at 23:33
  • @MattRaines yes - the way you've explained to do it above does seam much better than the answers in the other question. Thanks a lot! – Kian Cross Jun 11 '16 at 11:23