Home  >  Article  >  Backend Development  >  How to Use LIKE Operator with Parameters in PDO?

How to Use LIKE Operator with Parameters in PDO?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 09:26:11719browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn