When working with MySQL queries and the PDO library, it's crucial to effectively utilize the LIKE operator. Consider a scenario where you need to find usernames that start with the letter "a."
To correctly match usernames beginning with "a," the following code would suffice:
$term = "a"; $term .= "%"; // Adding the wildcard character $sql = "SELECT username FROM `user` WHERE username LIKE :term LIMIT 10"; $dbh = Connect::getInstance(); $stmt = $dbh->prepare($sql); $stmt->bindParam(':term', $term, PDO::PARAM_STR); $stmt->execute(); $data = $stmt->fetchAll();
The provided code incorrectly encloses $term in single quotes, leading to an incorrect query. By removing the inner single quotes and appending the wildcard "%" character correctly, the LIKE operator will match usernames starting with "a."
It's worth noting that PDO will automatically quote all string data during bindParam execution. This ensures that special characters are handled appropriately, preventing SQL injection vulnerabilities.
The above is the detailed content of How to Utilize LIKE with bindParam for Secure Username Search in MySQL PDO Queries?. For more information, please follow other related articles on the PHP Chinese website!