1
votes

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.

3
Please read the documentation on the functions you are using. Note the examples show you how to properly call object methods via this function. - Jonnix

3 Answers

0
votes

Try something like:

call_user_func_array(array($stmt,'bind_param'),$request['params']);
4
votes

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.

2
votes

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"));