Home >Database >Mysql Tutorial >How to Use LIKE with bindParam in MySQL PDO Queries?

How to Use LIKE with bindParam in MySQL PDO Queries?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 13:43:031041browse

How to Use LIKE with bindParam in MySQL PDO Queries?

Using LIKE in bindParam for a MySQL PDO Query (Fixed)

MySQL's LIKE operator allows for pattern matching in queries. When using bindParam to pass values for pattern matching, it's important to format the values correctly to ensure the query runs as expected.

Consider a query to find usernames that begin with the letter "a":

SELECT username 
FROM `user` 
WHERE username LIKE :term 
LIMIT 10

When using bindParam for the :term placeholder, the value needs to be passed as a string. However, if you add single quotes within the string, it will cause the query to match the literal value "'a%'" instead of "a%".

To resolve this, simply omit the inner single quotes:

$term = "a";
$term = "$term%";

This ensures that the bindParam value is passed as a proper string pattern that can be used in the LIKE clause effectively.

The above is the detailed content of How to Use LIKE with bindParam in MySQL PDO Queries?. 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