MySQLi, PHP, generate automated preparedStatement dynamically

Viewed 87

My basic Problem is to generate a automatised prepared Statement for DB Request

  $this->stmt_prep->bind_param("sss", $input[0], $input[1], $input[X]);

There are basically 2 "variables", Ive creating for this Request:

  1. the Datatype "ssss"
  2. the Userinput fields as "$Array_as_single_Values"

Assume:

$this->stmt_prep->bind_param("sss", $Array_as_single_Values);
$Array_as_single_Values = "Value1", "Value2", "ValueX"

I read out UserInput as

$Value = Array[$input1=> value1, $input2=> value2, $inputX=> valueX]

How isit possible, to convert each Values of this Array, as variable or its Value

Expected Result:

$Array_as_single_Values [$input1 => "value1"; 
$input2 => "value2"; 
$inputX => "valueX";]        //how to Convert this to needed Data?

$this->stmt_prep->bind_param("sss", $Array_as_single_Values);

same as:

$this->stmt_prep->bind_param("sss", $input1, $input2, $inputX);

or

$this->stmt_prep->bind_param("sss", "value1", "value2", "valueX");

Purpose: If I have 100 different Input Values, I do not have to re-wirte all statements

1 Answers

Use the splat operator ... :

$this->stmt_prep->bind_param("sssssssss", ...$Array_as_single_Values);

Small example :

function foo ($a, $b, $c)
{
    echo "$a $b $c";
}

$arr = [ "hello", "world", "42" ];

foo(...$arr); // output hello world 42

Without the operator, this causes an error "Fatal error: Uncaught ArgumentCountError: Too few arguments to function foo()"

If you want to automate the generation of "s" and are sure you'll use only VARCHAR types, you can re-write your function call like this :

$this->stmt_prep->bind_param(str_repeat("s", count($Array_as_single_Values)), ...$Array_as_single_Values);
Related