Search code examples
phparraysvariablesprepared-statement

PHP access array of variables as separated variables


I tried to write a class and method for select rows by the prepared statement.

I stuck in an interesting problem.

I can't assign an array of variables like $variables = [$var1, $var2, $var3]; to a function and use them separetely like my_function($var1, $var2, $var3); so I can have my_function($variables) is this possible? notice that, my_function won't accept an array.

in my code:

so when I run this:

$query = "SELECT * FROM books as b where b.id=?";
$result = Query::select($query, 'i', 1);

or when I run this:

$query = "SELECT * FROM books as b where b.id=? b.name=?";
$name = 'Sam';
$result = Query::select($query, 'is', 1,$name);

this method will execute:

public static function select($query, $string_of_types, ...$variables)
    {
        $mysql = new Mysqli(DB::$servername, DB::$username, DB::$password, DB::$databasename);
        $stmt = $mysql->prepare($query);

        ///////start mess up//////
        if(count($variables) == 1)
            $stmt->bind_param($string_of_types, $variables[0]);
        if(count($variables) == 2)
            $stmt->bind_param($string_of_types, $variables[0], $variables[1]);
        if(count($variables) == 3)
            $stmt->bind_param($string_of_types, $variables[0], $variables[1], $variables[2]);
        
        
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }

and it's working but I know I'm on the wrong foot.

how can I fix this mess up?

if I somehow magically, remove the [] around $variables, so everything will work fine. so I can write $stmt->bind_param($string_of_types, $variables);


Solution

  • What you're looking for is splat operator (...), that unpacks the array into the function argument list:

    $stmt->bind_param($string_of_types, ...$variables);