Reputation: 1766
I am currently writing a very basic PHP api which uses MySql databases for authentication and logging user data. I use prepared statements to avoid MySql injection. I attempted to make a generic function to handle and execute prepared queries as follows:
function query_prepared($sql, $type){//$type here is the string containing the characters of the type of the data to bind - e.g. 'sss' for string, string, string
$args = func_get_args();
$param_args = array();
for($i = 2; $i < count($args); $i++){
$param_args[$i - 2] = $args[$i];
}//the version of PHP I am using does not support variable length arguments so I have to store all of the arguments but the sql statement and parameter types in an array ($param_args)
$con = connect();//connects to the database
$statement = $con->prepare($sql);
if(!$statement)
error("Error while querying database. " . mysqli_error($con), ERR_QUERY_DB);
$statement->bind_param($type, $param_args);//<-- My problem is here - the bind_param function is supposed to pass arguments like this, $statement->bind_param($type, $var0, $var1, $var2...) but I only have an array of $var0, $var1, $var2... so it attempts to convert my array to a string before passing it to the bind_param function.
$statement->execute();
$statement->bind_result($result);
$rows = array();
$i = 0;
while($row = $result->fetch())
$rows[$i++] = $row;
$con->close();
return $rows;
}
I have done some reading and found the call_user_func_array
function but this obviously will not work in this instance.
Is there any way of passing my array ($param_args) as a variable length argument to the bind_params function.
Upvotes: 1
Views: 40
Reputation: 227270
You can use call_user_func_array
here. In fact, that's the correct way to do this.
array_unshift($param_args, $type); // <- Prepend $type to the array so it's passed too
// The 1st parameter is the callback. It's array($object, 'method')
call_user_func_array(array($statement, 'bind_param'), $param_args);
NOTE: bind_param
wants the args to be references, you'll have to tweak how you're setting $param_args
:
for($i = 2; $i < count($args); $i++){
$param_args[] =& $args[$i];
}
Upvotes: 1