PDO搜索返回Array() [英] PDO Search Returning Array()

查看:86
本文介绍了PDO搜索返回Array()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含示例数据的数据库

I have a database with the folliwng example data

http://i.stack.imgur.com/YOmX9.png

我正在使用PDO通过以下方式搜索名称(第三列,排除了标题):

I am using PDO to search the names (the 3rd column, I sort of excluded the titles) using the following:

search('items', 'name', 'Strong');

public function search($table, $column, $term){
        $command = "SELECT name FROM `$table` WHERE `$column` LIKE :$column";
        $query = $this->connection->prepare($command);
        $query->execute(array(":$column"=>$term));
        return $query->fetchAll();
    }

我的意愿是

Array ( )

为什么不返回任何内容?

Why is it not returning anything?

推荐答案

您可以尝试以下方法:

$query->execute(array(":$column" => "{$term}%"));

LIKE运算符需要知道在行中应该忽略值的哪些部分.做类似abc LIKE 'def'的事情和做abc='def'一样. %字符用于告诉LIKE应该忽略的内容.

The LIKE operator needs to know what parts of the values, in the rows, it should ignore. Doing something like abc LIKE 'def' is the same as doing abc='def'. The % character is used to tell LIKE what it should ignore.

因此,abc LIKE 'def%'告诉LIKE,它应该找到开始于 def的东西,并且后面可能没有任何东西.

So, abc LIKE 'def%' tells LIKE that it should find stuff that begins with def, and may or may not have anything after it.

%字符可以在搜索字符串中的任何位置多次使用.例如,abc LIKE '%def%'查找在值中任何地方 def的内容,而abc LIKE '%def'查找以def结尾的 内容.

The % character can be used anywhere, and multiple times, inside the search string. For example, abc LIKE '%def%' finds stuff that contains def anywhere in the value, and abc LIKE '%def' finds stuff that ends with def.

字符串中的{}只是插值定界符.在对数组值进行插值时,需要使用它们,但是有些人也将它们用于常规变量.您并不严格需要它们.您可以将其写为"$term%",但是我发现花括号对区分变量和其余字符串很有帮助.

The {} inside the string are just interpolation delimiters. When you interpolate array values you need to use them, but some people also use them for regular variables. You do not strictly need them. You could just write it, "$term%", but I find the curly braces to be helpful for differentiating variables from the rest of the string.

注意:如果您知道正则表达式,则SQL %字符非常类似于正则表达式中的.*?.

Note: If you know regular expressions then the SQL % character is much like .*? in regex.

这篇关于PDO搜索返回Array()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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