Home >Database >Mysql Tutorial >How to Correctly Use LIKE Queries with PDO Parameters?
Using LIKE Queries in PDO
When trying to implement LIKE queries in PDO, you may encounter issues like the one described in the query below:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'"; $params = array($var1, $var2); $stmt = $handle->prepare($query); $stmt->execute($params);
This query will likely return no results, even when $var1 and $var2 contain valid search words. The error lies in the incorrect inclusion of % signs.
To correctly use LIKE in PDO, the % signs should be included in the $params array, not in the query itself. Here's the corrected code:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?"; $params = array("%$var1%", "%$var2%"); $stmt = $handle->prepare($query); $stmt->execute($params);
By enclosing the variables in % signs within the $params array, you ensure that the % characters are substituted into the query correctly. Without this modification, the PDO prepared statement will treat the % signs as part of the literal string value, resulting in an incorrect query.
The above is the detailed content of How to Correctly Use LIKE Queries with PDO Parameters?. For more information, please follow other related articles on the PHP Chinese website!