为什么在 MySQL PDO 查询中使用'LIKE”时'bindParam”失败?

Susan Sarandon
发布: 2024-11-13 10:36:02
原创
139 人浏览过

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%'";
登录后复制

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".

以上是为什么在 MySQL PDO 查询中使用'LIKE”时'bindParam”失败?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板