Home > Article > Backend Development > How to Use LIKE Operator with Parameters in PDO?
Implement LIKE Query in PDO
In PDO, when using the LIKE operator, it's crucial to include the % signs in the parameters, not within the query itself. This is because PDO prepared statements encapsulate values in quotes, which can interfere with the % placeholders.
For example, consider the following query:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'"; $params = array($var1, $var2);
When this query is prepared, the % signs will be encapsulated in quotes, resulting in a query like this:
SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%'
Consequently, the query will not return any results because the double quotes disrupt the intended functionality of the LIKE operator.
To rectify this issue, the % signs should be included in the parameters instead:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?"; $params = array("%$var1%", "%$var2%");
With this modification, the prepared query will correctly search for addresses containing $var1 or $var2.
The above is the detailed content of How to Use LIKE Operator with Parameters in PDO?. For more information, please follow other related articles on the PHP Chinese website!