Home > Backend Development > PHP Tutorial > How to Achieve Dynamic Parameter Binding in PHP MySQLi?

How to Achieve Dynamic Parameter Binding in PHP MySQLi?

Susan Sarandon
Release: 2024-12-06 00:46:11
Original
914 people have browsed it

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();
}
Copy after login

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>';
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template