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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3