With mounting a query dynamically depending on a typed string

Asked

Viewed 66 times

1

I’m mounting a search in the database where the user informs an example text: "how to configure windows".

Currently I have a select which works as follows:

$query = "SELECT resposta FROM suporte where pergunta like '%".$s."%'";

Where $s has the value to configure windows.

My idea would be to take this string and break word by word where the select final would be:

SELECT resposta FROM suporte where pergunta like '%como%' and pergunta like '%configurar%' and pergunta like '%o%' and pergunta like '%windows%'

Someone would have an example of how to proceed in this case?

Detail I’m using PHP as a language

  • 1

    Do you know the concept of Elastic search? Maybe it solves your problem.

  • 4

    It would be interesting if the people who denied the question explained why.

  • Hello Eder Luca, it is very important we inform the language you are using to facilitate your help

  • Depending on the language you can use interpolation!

  • sorry I just forgot to comment I’m using the php language

1 answer

0

I put as a method to simplify:

function constructQuerySearch($s) 
{ 
    $results = explode(' ', $s);

    $query_parse = array();
    if (count($results)) {

       $query = "SELECT resposta FROM suporte WHERE pergunta LIKE '%" . $results[0] . "%'";
       foreach($results as k =>  $result) {
            if ($k > 0) {
               $query .= ' AND ';
               $query_parse[] = "pergunta like '%$result%'"   
            }
       }
       $query . implode(' AND ', $query_parse);
    }

    return $query;
}

Obs: But I would use "OR" instead of "AND", not to limit your query.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.