How to Avoid Incorrect Queries When Using LIKE in PDO?

Susan Sarandon
Release: 2024-11-11 12:54:02
Original
991 people have browsed it

How to Avoid Incorrect Queries When Using LIKE in PDO?

Implementing LIKE Queries Correctly in PDO

When attempting to execute a LIKE query in PDO, it's important to ensure proper syntax to retrieve accurate results. In the query provided, the issue lies with the placement of the % wildcard characters.

The correct syntax for LIKE queries in PDO is to include the % signs within the $params array, rather than the query itself. Here's an example:

$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
Copy after login

If the % signs were included within the $params array, the generated query would look like the following:

SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%'
Copy after login

However, in the original query provided, the % signs were included within the query itself:

$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
Copy after login

When the query is executed, the prepared statement quotes the values inside of an already quoted string, resulting in an incorrect query. By moving the % signs to the $params array, the intended query will be executed correctly.

The above is the detailed content of How to Avoid Incorrect Queries When Using LIKE in PDO?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template