Search in 2 fields at the same time

Asked

Viewed 625 times

0

Código da pesquisaEae,

I have two fields in a mysql table, Description and degree.

how do I do when I search type WORD and 4 ( being WORD from the Description field and 4 from the Grade field? a result appears?

PS.: Both description and degree are in text mode.

PS2.: if I search separately it finds result (like, if I type only WORD it finds, and if I search only 4 it finds also)

  • First post the query you’re using, so we can help you.

  • @Mauroalexandre put it there ^^

  • A AND solve it, right? Like tal campo LIKE '%sua palavra%' AND tal campo LIKE '%outra palavra%', I guess that’s it, I didn’t quite understand your question

  • @Wotonsampaio is like this, many times what will type in this system is present in more than one field, but the query does not show the result when I type something that is present in the two fields, using the example I put in the question if I type word 4, shows no result, even having word in the Description field and 4 in the grade field

2 answers

0

From what I understand you want to do a query that looks in two fields at once if something is in one field or the other...if that’s it and only use OR.

If you want to search for two words typed in the same input, you have to treat them first. I don’t know much about php, but there must be some function that separates a string, like a split() where you pass as argument a separator, this separator can be a space, a comma or a tab.

  • Yes, you got it right, I’ve tried with the OR, but the same result. If I type only WORD it finds in the description field, if I type only 4 it finds in the grade field, but if I type WORD 4 it does not find in either of the two fields.

  • @Eduardorodrigues Rodrigo is right, you must use a explode in vdd, split is for java kkkkkk, you can use a foreach to query, I’ll send an example in a reply, it is more organized

0


Making the explode and assembling your query:

//Separo a frase por espaço
$v = explode(" ", "palavra 4");

$query = 'SELECT * FROM sua_tabela WHERE ';

foreach ($v as $key => $value) {
   $query .= "campo_1 LIKE '%" . $value . "%' OR campo_2 LIKE '%" . $value . "%' OR ";
}

//Retiro o último 'OR '
echo substr($query, 0, -3);

The example prints: SELECT * FROM sua_tabela WHERE campo_1 LIKE '%palavra%' OR campo_2 LIKE '%palavra%' OR campo_1 LIKE '%4%' OR campo_2 LIKE '%4%'

This example is very generic, but with it you can understand how you can build your query very simply

Browser other questions tagged

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