"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 with BindParam in MySQL PDO Queries?

How to Correctly Use LIKE with BindParam in MySQL PDO Queries?

Published on 2024-11-16
Browse:804

How to Correctly Use LIKE with BindParam in MySQL PDO Queries?

Properly Using LIKE with BindParam in MySQL PDO Query

When attempting to perform LIKE searches with bindParam in MySQL PDO queries, it's essential to use the correct syntax to ensure accurate results.

Optimized Syntax

To match usernames starting with "a" using bindParam, the correct syntax is:

$term = "a%";

In contrast, the syntax provided in the original question, "$term = "'$term%'", is incorrect as it places unnecessary inner single quotes around the $term value, which would result in searching for 'a%' instead of a%.

bindParam's Role

bindParam is responsible for automatically quoting string data when it's inserted into SQL statements. Therefore, appending single quotes manually is not necessary and can lead to incorrect results.

Revised Code

Using the optimized syntax, the revised code would be:

$term = "a%";

$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();
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