"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Correctly Use LIKE Queries with PDO Parameters?

How to Correctly Use LIKE Queries with PDO Parameters?

Posted on 2025-03-26
Browse:819

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.

Latest tutorial More>

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