Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a database with the folliwng example data

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

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

and my reutrn is

Array ( )

Why is it not returning anything?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can try this:

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

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.

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

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...