php 在 bindParam 中使用 LIKE 进行 MySQL PDO 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11068230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:41:36  来源:igfitidea点击:

Using LIKE in bindParam for a MySQL PDO Query

phpmysqldatabasepdo

提问by Dan

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

回答by Harald Brinkhof

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%'而不是a%

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

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

回答by Dip

You can use bindValue , suppose you are having a $query = "search string"

您可以使用 bindValue ,假设您有一个$query = "search string"

$stmt->bindValue(':term', $query.'%'); // this will do like search for "search term XXXXX"

similarly

相似地

$stmt->bindValue(':term', '%'.$query.'%');

or

或者

$stmt->bindValue(':term', '%'.$query);