Home > Backend Development > PHP Tutorial > How to Implement LIKE Queries with Placeholders in PDO?

How to Implement LIKE Queries with Placeholders in PDO?

Susan Sarandon
Release: 2024-11-12 01:34:03
Original
436 people have browsed it

How to Implement LIKE Queries with Placeholders in PDO?

Implement LIKE Query in PDO

When working with LIKE queries in PDO, it's crucial to understand how to correctly incorporate placeholders and bind variables. This article addresses a problem faced by a user implementing LIKE queries in PDO, where their query was failing to return results.

The original query, as provided by the user, attempted to use placeholders with appended percentage signs:

$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
Copy after login

However, this approach is incorrect. The percentage signs should be included in the bind variables, not in the query itself:

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

By enclosing the variable values with percentage signs in the bind variables, the generated query ensures that the LIKE clauses will search for addresses containing the specified words. Without this adjustment, the query would generate something like:

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

This query would fail because the percentage signs are embedded within quotes, causing the search to look for addresses that contain the exact text "foo" or "bar", not words containing those terms.

The above is the detailed content of How to Implement LIKE Queries with Placeholders 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