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);
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!