Flexible Binding for Multiple Parameters in MySQLi Query
Currently, to bind multiple parameters into an MySQLi query, the following repetitive structure is employed:
if ($words_total == 1) { $statement -> bind_param("s", $words[0]); } // ... more if-else conditions for each possible number of parameters ...
To calculate the number of question marks needed in the query, the following code is used:
$marks = ""; for($i = 1; $i<=$words_total; $i++) { if ($i == $words_total) $marks .= "?"; else $marks .= "?,"; }
Improved Approach with Argument Unpacking
Fortunately, PHP 5.6 introduces the argument unpacking operator (...), which simplifies the binding of multiple parameters. Instead of relying on static type strings, the operator can be used with an array:
// create an array of parameter values $parameters = [$words[0], $words[1], ... $words]; // create a type string dynamically $types = str_repeat('s', count($parameters)); // bind the array using argument unpacking $statement -> bind_param($types, ...$parameters);
With this approach, the binding can be handled dynamically regardless of the number of parameters.
The above is the detailed content of How Can I Efficiently Bind Multiple Parameters in MySQLi Queries?. For more information, please follow other related articles on the PHP Chinese website!