简体   繁体   中英

Autocomplete search query mysql

I'm having trouble with a search query.

I have two columns named 'artist' & 'title' . But for an autocomplete function I need a SQL query to search in these columns while someone is typing. There is a very simple solution I know of which is the following:

SELECT * FROM music WHERE artist LIKE '%".$term."%' OR title LIKE
'%".$term."%'

$term = textboxvalue

But this query has a couple of huge problems. Let's say the artist is 'DJ Test' and the title is 'Amazing Test Song' . If I type 'DJ' it works fine. But when I type 'DJ Amazing' . No search results were found. Obviously ofcourse but I can't figure how to fix it.

But that's not the only problem. If someone types in 'DJ Test - Amazing Test Song' it has to ignore the '-'.

So my question is, what does my search query look like when I can type anything like 'Amazing DJ Test' and still give back what I need?

Try something like this.

I think it should work but I haven't tested it.

    $terms = explode(' ', $term);

    foreach($terms as $term){

        $query  = SELECT * FROM music WHERE artist LIKE '%".$term."%' OR title LIKE '%".$term."%'

        return $query;

    }

Should hopefully work

You would have to make it split the search string up into words, then add those words as lookup criteria by appending them to the query.

First make an array that contains each individual word from the search string.

$search  = 'DJ TEST Amazing Test Song';
$search_terms = explode(" ", $search);

Then alter the query for each search term:

foreach($search_terms as $search_term) {
     //append OR to query with $search_term
     $query .= "OR artist LIKE '%".$search_term."%' OR title LIKE '%".$search_term."%'";

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM