Dividing up multiword $_POST input

时间:2015-10-30 21:36:45

标签: php mysql sql

I am trying to have a PHP form that takes in a text input, then queries the underlying MySQL table.

<form method="GET" action="search.php" name ="SearchBar">
            <input type="text" name"search">
            <input type="submit" value="Search">
</form>

The schemas of the tables I am querying are
Movie(id, title, year, rating, company)
Actor(id, last, first, sex, dob, dod)

For Movie, I think it'll be easy because I just make a query with WHERE title LIKE '%".$_POST['search']."%' something along that line. But for Actor, since the name is divided into two parts (last, first), I think I need to break down my inputs by words so that I can compare each word to the attributes. (so that if input is 'Hanks Tom' or 'Tom Hanks', my query will be able to find the actor Tom Hanks from either input)

Is there a way to achieve this, or possibly a smarter way to approach this?

2 个答案:

答案 0 :(得分:2)

You have to search every combination of the input to see if one of them match the first or last name. Also keep in mind that first and last are reserved words for MySQL. You can use something like the following.

$input = 'Tommy Lee Jones';

$names = explode(' ', preg_replace('/(\s)+/', ' ', $input););
$temp = array();

foreach($names as $key) {
    $temp[] = "`first` LIKE '%$key%'";
    $temp[] = "`last` LIKE '%$key%'";
}

$s = ' AND ( '.implode(' OR ', $temp).' )';

echo $s;

Result:

AND ( `first` LIKE '%Tommy%' OR `last` LIKE '%Tommy%' OR `first` LIKE '%Lee%' 
OR `last` LIKE '%Lee%' OR `first` LIKE '%Jones%' OR `last` LIKE '%Jones%' )

答案 1 :(得分:1)

You could try something like :

select [insert other selects here], concat(`first`, ' ', `last`) fullname
from actors where fullname like "%name%"

Hope this helps!