How do I create a function like bind_param () in PHP?
I'm trying to write a small MySQL wrapper that has some basic functionality that I need for my code. This is for testing purposes and for getting to know PHP a little more.
The problem I am facing is the following:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
The above is the exact definition that I find on the internet, but I cannot make my function look like this (syntax errors or the server says: I need a var of type "mixed").
public function bind($types, $values)
{
$this->statement->bind_param($types, $values);
}
The above is roughly what I would like to achieve, but even searching the internet I cannot seem to find a solution.
source to share
public function bindParam($types)
{
/* For types, the next rules count:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$fetchedParameters = func_get_args();
$parameters = "\"$types\"";//Create a variable that holds the types of the statement
for($i = 1; $i < count($fetchedParameters);$i++)
{
$parameters .= ",\$fetchedParameters[$i]"; //Each variable name gets added to parameters(it needs to be the variable name, not the value!!)
}
eval("\$this->statement->bind_param($parameters);");//Assemble the statement and execute it.
}
This is pretty much what I developed, my options are not user supplied, so there shouldn't be any security issues. This completely fixes my problem.
source to share
The "mixed" type doesn't exist, it just says that the passed parameter can be a string, or it can be an integer or anything. You must write your function with one parameter, $ types, and all other parameters coming from func_get_args (). This passes all the parameters given to this function, so you can treat them like an array:
function bind_param(string $types)
{
$args = func_get_args();
print_r($args);
}
bind_param("foo", "bar", 123, false, array("a","b"));
Note that it will include the first $ types parameter as well.
source to share