Question

I have a function I am creating inside of a custom database class. The function is designed to take parameterized SQL, sanitize the input and execute it.

The only issue I am having is with the last uncommented line. I have a variable of type array, but I need to pass each value in the array as a separate argument. How would I go about doing this?

function do_query($sql, $values){
    if(!isset($this->connect_error)){
        if(tg_debug == true){
            print "Query Executing! <br />";
        }
        $num_vals = count($values);
        $i = 0;
        $type = "";
        while($i < $num_vals){
            if(is_int($values[$i]) == true)
                $type .= "i";
            elseif(is_string($values[$i]) == true)
                $type .= "s";
            $i++;
        }
        $i = 0;
        while($i < $num_vals){
            // security stuff goes here...
            $values[$i] = $this->escape_string($values[$i]);
            $i++;
        }

        $expr = $this->prepare($sql);
        print_r($values);
        // $values is still an array, extract values and convert to a seperate argument
        $expr->bind_param($type, $value);
        //$expr->execute();

    }
}

Example query: $class->do_query("INSERT INTOtable(id, value) VALUES (?, ?)", array(3, "This is a test"));

Was it helpful?

Solution

Use the ReflectionMethod class

...
$bindParamReflection = new \ReflectionMethod($expr, 'bind_param');
$args = $values;
array_unshift($args, $type);
$bindParamReflection->invokeArgs($expr, $args);
...

OTHER TIPS

You can use call_user_func_array():

$args = $values;
array_unshift($args, $type);
call_user_func_array(array($expr, 'bind_param'), $args);

This will be greatly simplified when the splat operator is added to the language, which should happen in 5.6:

$exp->bind_param($type, ...$values);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top