Home > Database > Mysql Tutorial > Why Does `bindParam` Fail When Using `LIKE` in MySQL PDO Queries?

Why Does `bindParam` Fail When Using `LIKE` in MySQL PDO Queries?

Susan Sarandon
Release: 2024-11-13 10:36:02
Original
235 people have browsed it

Why Does `bindParam` Fail When Using `LIKE` in MySQL PDO Queries?

Correcting LIKE Syntax When Using bindParam for MySQL PDO Queries

In MySQL PDO queries, using LIKE with bindParam can be tricky. This question demonstrates a common issue faced when attempting to match usernames beginning with a specific string.

The incorrect syntax provided in the question uses inner single quotes around the $term variable:

$term = "'$term%'";
Copy after login

To fix this, simply remove the inner single quotes:

$term = "$term%";
Copy after login

When using bindParam, PDO automatically handles string quoting. Adding unnecessary quotes within the $term variable can result in incorrect LIKE matching.

The corrected statement should look like this:

$sql = "SELECT username 
        FROM `user` 
        WHERE username LIKE :term 
        LIMIT 10";      

$core = Connect::getInstance();

$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':term', $term, PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
Copy after login

This will correctly match usernames that begin with the $term variable, for example "a".

The above is the detailed content of Why Does `bindParam` Fail When Using `LIKE` in MySQL PDO Queries?. 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