PHP Search system ignore uppercase letters and add keywords

Asked

Viewed 881 times

1

I have a simple search system that searches for values in the comic book and displays on the page. In the table I have a column called palavraschaves where the words I leave as a query parameter are registered. I need two things. The first is that when typing the word with uppercase or lowercase letter it understands the same way without I need to register both in the BD. The second thing is that it adds the words in the search. For example: I entered the words in the table in the following order; house building roof. If I type roof house does not return me anything, just search for one of the two. I want him to search for the two.

Code

$busca = trim($_POST['busca']);
$sql = mysqli_query($conn, "SELECT * FROM pesquisa_clientes WHERE palavraschaves LIKE '%".$busca."%' ORDER BY nome");
$numRegistros = mysqli_num_rows($sql);
if ($numRegistros != 0) {


echo "<h4 class='result'>Resultados para: <b> " . $busca . "</b></h4><br />";

        while ($usuario = mysqli_fetch_object($sql)) {

echo "<div id='resultados'>";
echo "<img src='images/clientes/".$usuario->logo."' alt='Foto de exibição' /><br />";
echo utf8_encode("<h4><b> " . $usuario->nome . "</b></h4><br />");
echo utf8_encode("<p><span><b> " . $usuario->subcategoria . "</b></span></p><br /><br />");
echo utf8_encode("<p><b>Bairro:</b> " . $usuario->bairro . "</p><br />");
echo "<p><b>Telefone:</b> " . $usuario->telefone . "</p><br />";
echo "<a href='". $usuario->link_cliente. "'><b>Saiba Mais</b></a><br /><br />";
echo "</div>";
}
} else {
        echo "<h4 class='result'>Nada foi encontrado com a palavra:<b> ".$busca."</b></h4>";
}
    ?>
  • 1

    I recommend limiting the question to a specific problem.

  • Could you show how the words are inserted in the database ? I don’t know if they are inserted separately, or the way the user type in the query. Show me this.

  • I separated by simple space: home car plastic table

  • The first case has several subjects here: https://answall.com/questions/144251/como-trata-igualmente-strings-accentuas-sem-acento-num-like/144265#144265, https://answall.com/questions/192156/sql-like-%C3%A9-case-sensitivecaso-sensitive/192373#192373, https://answall.com/questions/72139/qual-encodes%C3%A7%C3%A3o-de-characters-collation-devo-usar-em-mysql/72142#72142.....

  • Turkish, choose a database/table meeting ending in _ci (meaning "case insensitive"), this will solve the case of upper or lower case letters. For the search problem, I recommend using mysql match Against. I already gave an answer once explaining the use of match Against, see this answer: https://answall.com/questions/187858/fazer-uma-busca-independente-da-ordem-das-palavras-chave/187895#187895

  • Friends. I didn’t try the code you gave me because Leo’s solved my previous problem. But I changed the question because a new one came up.

  • I reversed the last edition because it changes the meaning, invalidating the existing answers so far.

  • If you want to kill two rabbits in one shot, put the bench as utf8_general_ci. So you will not need to make as much effort for both cases, accentuation and high or low cash.. I stress that is not "the solution", but an option.

  • Edited response to meet accent

Show 4 more comments

2 answers

4


  • Regarding capital letters and minuscules Your question is not very clear. I will assume that the words in the database are all in minuscules and the user type uppercase or minuscule. In this case just use the function strtolower which converts all characters to lower case

  • About "add key words" use REGEXP, explode and implode.

DEMO

$busca = trim($_POST['busca']);
//para remover os espaços duplicados.
$busca = preg_replace('/\s(?=\s)/', '', $busca);
//tudo em minusculas
$busca = strtolower($busca)

//quando uma pessoa digitar umas palavras, elas são explodidas pelo espaço
$exp = explode(" ", $busca); // separando pelo espaço

//e em seguida são implodidas pela | (barra vertical)
$imp = implode("|", $exp); // unindo os valores pela |

//a consulta é como segue
SELECT * FROM pesquisa_clientes WHERE palavraschaves REGEXP '$imp' ORDER BY nome

A | (vertical bar) is necessary for the use of REGEXP, it symbolizes the OR "or", that is, fetch between the values separated by | (vertical bar).

To convert accents you can use the function

Function TirarAcento( $texto ) 
{
    $array1 = array(   "á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç"); 

    $array2 = array(   "a", "a", "a", "a", "a", "e", "e", "e", "e", "i", "i", "i", "i", "o", "o", "o", "o", "o", "u", "u", "u", "u", "c"); 

    return str_replace( $array1, $array2, $texto ); 
}  

 $busca = trim($_POST['busca']);
 $busca = preg_replace('/\s(?=\s)/', '', $busca);

 $busca = strtolower($busca);

 $busca = TirarAcento($busca);
 ............................
 ............................
 ............................

call the function TirarAcento after the function strtolower

Want to know why? Hover your mouse in the area below yellowed

because the function TirarAcento is making the exchange of accented letters only for minuscules, therefore it is indispensable to put the search terms first in minuscules with the function strtolower

  • Leo. Your example saved me. Exactly what I was looking for. I changed my question and the code as you passed it and now I have just one more question. How do I convert the accents? For example: I registered the words without accent in the comic book, but I want when searching with an accent it does the conversion. So it would be correct or I should register with accent and convert at the time of the search?

  • It includes the line and gives me the error: Warning: mysqli_num_rows() expects Parameter 1 to be mysqli_result, Boolean Given in /var/www/html/oabobreiro.com.br/web/result.php on line 365. Align 365 looks like this: $numRegisters = mysqli_num_rows($sql);

  • I’ll put a function for the accented characters

  • Leo. Wonderful. Its code is simple to understand, besides being a clean code is extremely functional. I am perfecting myself in PHP and mysqli and today you have been a great teacher to me. Where I give you a star?

0

About the uppercase and lowercase letters, I believe that the best way is for you to define how you will save the words in the database, if it is uppercase for example, when reading the words that the user typed you turn that string uppercase with strtoupper(string). The second part of the problem, you can break the string that the user typed with the explode, done this, you will have an array with the captured words, ai just use the implode and separate the values of the arrays by commas in your select.

would look something like this:

$busca = trim($_POST['busca']);
//transformo tudo em maiúsculo
$busca = strtoupper($busca)
//quebro a string nos espaços, e gravo no array
$array= explode(" ", $busca)
//where IN (valor1, valor2,valor3), uso o implode para coloca a virgula após cada valor do array
$sql = mysqli_query($conn, "SELECT * FROM pesquisa_clientes WHERE palavraschaves in ('.implode(',', array_map('intval', $array)).') ORDER BY nome");

I don’t know if this is working because I didn’t test it, but here’s the idea

Browser other questions tagged

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