Home >Backend Development >PHP Tutorial >How Can I Dynamically Bind MySQL Parameters in PHP?
Dynamically Binding MySQL Bind Parameters in PHP
As you've discovered, the bind_param method in PHP's MySQLi extension can be limited in terms of dynamically handling multiple parameters or parameterless queries. Below are strategies for addressing this issue:
Using call_user_func_array
The following code snippet allows you to dynamically create and bind an array of parameters:
if (strnatcmp(phpversion(), '5.3') >= 0) { $refs = array(); foreach ($arr as $key => $value) $array_of_params[$key] = &$arr[$key]; call_user_func_array(array(&$stmt, 'bind_params'), $array_of_params); }
Using PHP 5.6 Syntax
In PHP 5.6 and later, you can take advantage of the unpacking operator and get_result() method:
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:
$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>'; }
These solutions provide more flexibility and dynamic binding capabilities for your MySQL queries.
The above is the detailed content of How Can I Dynamically Bind MySQL Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!