在 bindParam 中使用 LIKE 进行 MySQL PDO 查询 [英] Using LIKE in bindParam for a MySQL PDO Query

查看:31
本文介绍了在 bindParam 中使用 LIKE 进行 MySQL PDO 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了多个关于如何编写这些查询的示例,但是在使用 bindParam

I've read multiple examples on how these queries should be written but I'm struggling to get this specific like to run when using bindParam

这是匹配以 a 开头的用户名的正确方法吗?

Would this be the correct way to match usernames that begin with a?

$term = "a";
$term = "'$term%'";

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

推荐答案

不,你不需要内部单引号,所以只需 $term = "$term%";

No, you don't need the inner single quotes so just $term = "$term%";

您现在运行的语句将尝试匹配 'a%' 而不是 a%

The statement you're running now would try to match 'a%' instead of a%

bindParam 将确保所有字符串数据在提供给 SQL 语句时自动正确引用.

bindParam will make sure that all string data is automatically properly quoted when given to the SQL statement.

这篇关于在 bindParam 中使用 LIKE 进行 MySQL PDO 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆