Home > Backend Development > PHP Tutorial > How to Efficiently Build Dynamic LIKE Queries with mysqli Prepared Statements?

How to Efficiently Build Dynamic LIKE Queries with mysqli Prepared Statements?

Linda Hamilton
Release: 2024-12-03 08:23:10
Original
272 people have browsed it

How to Efficiently Build Dynamic LIKE Queries with mysqli Prepared Statements?

Dynamic LIKE Queries Using mysqli Prepared Statements

This question addresses the issue of creating a prepared statement with a variable number of LIKE conditions based on user input. The provided PHP code attempts to construct the statement, but there is an error related to the formatting of the LIKE clauses.

The key problem lies in where the percent signs (%) are placed around the parameters (?) in the LIKE clauses. Instead of wrapping the parameters, the percent signs should go around the placeholders, as shown below:

foreach ( $search_exploded as $search_each ) {
    $x ++;
    if ( $x == 1 ) {
        $construct .= "name LIKE %??%";
    } else {
        $construct .= " or name LIKE %??%";
    }
}
Copy after login

This correction ensures that the parameter values (e.g., "my name") are correctly bound to the LIKE clauses.

Additionally, the code uses a concatenated string ($construct) to build the WHERE clause. However, a more efficient and secure approach is to use a bind_param() placeholder array for all parameters, as shown below:

$where_params = [];
foreach ( $search_exploded as $search_each ) {
    $where_params[] = "%{$search_each}%";
}

$query = "SELECT * FROM info WHERE name LIKE ?";
$stmt = mysqli_prepare( $conn, $query );
mysqli_stmt_bind_param( $stmt, "s", ...$where_params );
Copy after login

This method gracefully handles any number of LIKE conditions and eliminates the risk of SQL injection vulnerabilities.

With these modifications, the dynamic LIKE query can correctly search for records based on multiple user-defined criteria.

The above is the detailed content of How to Efficiently Build Dynamic LIKE Queries with mysqli Prepared Statements?. 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