Home >Backend Development >PHP Tutorial >How to Achieve Dynamic Parameter Binding in PHP MySQLi?
Dynamic Binding for PHP MySQLi
Dynamic Parameter Binding
In PHP MySQLi, the bind_param() method allows for the binding of parameters to a prepared statement. However, for dynamic binding, where parameters can vary in quantity and type, the default method falls short.
Solution
To overcome this limitation, the following solution can be employed:
Using Unpacking Operator and get_result()
With PHP 5.6 and later, the unpacking operator (...) and get_result() can be used to simplify dynamic binding:
public function get_custom_result($sql, $types = null, $params = null) { $stmt = $this->mysqli->prepare($sql); $stmt->bind_param($types, ...$params); if (!$stmt->execute()) return false; return $stmt->get_result(); }
Example
This example illustrates how to dynamically bind parameters and retrieve the result:
$mysqli = new database(DB_HOST, DB_USER, DB_PASS, DB_NAME); $output = new search($mysqli); $sql = "SELECT * FROM root_contacts_cfm WHERE root_contacts_cfm.cnt_id = ? AND root_contacts_cfm.cnt_firstname = ? ORDER BY cnt_id DESC"; $res = $output->get_custom_result($sql, 'ss', array('1', 'Tk')); while ($row = $res->fetch_assoc()) { echo $row['fieldName'] . '<br>'; }
This approach provides a dynamic way to bind parameters based on the parameters passed to the function call.
The above is the detailed content of How to Achieve Dynamic Parameter Binding in PHP MySQLi?. For more information, please follow other related articles on the PHP Chinese website!