1

I'm trying to prepare a sql statement with unknown amount of parameters! These parameters are past on in an array. The normal syntax for the function would be:

$stmt->bind_param("string of types",param1,param2,...,paramN)

The problem is I dont know how to add parameters in the function $stmt->bind_param out of an array

I have this code but it does not work:

$stmt= $conn->prepare($request['query']);
if(isset($request['params'])){
call_user_func_array('$stmt->bind_param',$request['params']);
}
$stmt->execute();
$result = $stmt->get_result();

$request['params'] contains the right parameters that need to be added in the function.

But the call_user_func_array gives me this error:

call_user_func_array() expects parameter 1 to be a valid callback, function '$stmt->bind_param' not found or invalid function.

I think call_user_func_array might not be the right function to use! I googled for hours but could not find a solution for this small problem.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Brecht Valcke
  • 67
  • 1
  • 11
  • 1
    Please read [the documentation](http://php.net/call_user_func_array) on the functions you are using. Note the examples show you how to properly call object methods via this function. – Jonnix Sep 27 '16 at 14:38

3 Answers3

4

If you're using PHP 5.6+, you could also use the splat operator rather than using call_user_func_array, e.g.

$stmt->bind_param($types, ...$request['params']);

This would be neater for your use-case, since there's an initial argument to bind_param that would otherwise need to be shift-ed onto the front of the array of arguments.

iainn
  • 16,826
  • 9
  • 33
  • 40
  • I'm not using 5.6+! Because it's just a test on a usbwebserver and thats 5.2 but your solution would be the best if I had that version – Brecht Valcke Sep 27 '16 at 15:17
2

To use a method as a callback parameter to call_user_func_array, use an array with the object name and the method name in it as the callback parameter.

Check PHP's call_user_func_array documentation page for further explanations: http://php.net/manual/pt_BR/function.call-user-func-array.php

// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
Melanef
  • 199
  • 5
0

Try something like:

call_user_func_array(array($stmt,'bind_param'),$request['params']);
Philipp Dahse
  • 749
  • 3
  • 9
  • Thank you! The problem is it gives a value and not a reference: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given – Brecht Valcke Sep 27 '16 at 15:10
  • Solved it! I used `call_user_func_array(array($stmt,'bind_param'),refValues($request['params']));` with this function i got on the internet:`function refValues($arr){ if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+ { $refs = array(); foreach($arr as $key => $value) $refs[$key] = &$arr[$key]; return $refs; } return $arr; }` – Brecht Valcke Sep 27 '16 at 15:28