Implement LIKE Query in PDO
When working with LIKE queries in PDO, it's crucial to understand how to correctly incorporate placeholders and bind variables. This article addresses a problem faced by a user implementing LIKE queries in PDO, where their query was failing to return results.
The original query, as provided by the user, attempted to use placeholders with appended percentage signs:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'"; $params = array($var1, $var2);
However, this approach is incorrect. The percentage signs should be included in the bind variables, not in the query itself:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?"; $params = array("%$var1%", "%$var2%");
By enclosing the variable values with percentage signs in the bind variables, the generated query ensures that the LIKE clauses will search for addresses containing the specified words. Without this adjustment, the query would generate something like:
SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%'
This query would fail because the percentage signs are embedded within quotes, causing the search to look for addresses that contain the exact text "foo" or "bar", not words containing those terms.
The above is the detailed content of How to Implement LIKE Queries with Placeholders in PDO?. For more information, please follow other related articles on the PHP Chinese website!