Home > Database > Mysql Tutorial > How to Correctly Implement LIKE Queries with PDO Using Two Variables?

How to Correctly Implement LIKE Queries with PDO Using Two Variables?

DDD
Release: 2024-12-07 12:17:12
Original
745 people have browsed it

How to Correctly Implement LIKE Queries with PDO Using Two Variables?

Implementing LIKE Queries with PDO

When implementing LIKE queries in PDO, one may encounter challenges ensuring correct syntax. This question highlights an issue encountered while attempting to search for records based on two variables using LIKE.

To execute a LIKE query with PDO, it's crucial to include the % wildcard character within the parameters, not the query string. Here's the correct code:

$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
Copy after login

In the previous attempt, the % characters were included in the query string, resulting in a malformed query. The prepared statement would quote the values inside the already quoted string, leading to incorrect results.

By including the wildcards in the parameters, the query will be correctly executed, searching for records where the address column contains either $var1 or $var2 (or both).

The above is the detailed content of How to Correctly Implement LIKE Queries with PDO Using Two Variables?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template