在bindParam中使用LIKE作为MySQL PDO查询

时间:2022-02-18 00:10:09

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

我已经阅读了关于如何编写这些查询的多个示例,但在使用bindParam时,我很难实现这种特定的运行方式

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

这是匹配以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();

1 个解决方案

#1


23  

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

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

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

现在正在运行的语句将尝试匹配“a%”而不是“%”

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

bindParam将确保在给定SQL语句时,所有字符串数据都被自动引用。

#1


23  

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

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

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

现在正在运行的语句将尝试匹配“a%”而不是“%”

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

bindParam将确保在给定SQL语句时,所有字符串数据都被自动引用。