Maison > Article > base de données > Pourquoi « bindParam » échoue-t-il lors de l'utilisation de « LIKE » dans les requêtes MySQL PDO ?
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%'";
To fix this, simply remove the inner single quotes:
$term = "$term%";
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();
This will correctly match usernames that begin with the $term variable, for example "a".
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!