How to create a PHP and MYSQL search

Asked

Viewed 150 times

0

Database: Registration

Table = People

Records: id, name, sex and phone

index php.

<form method="post" action="index2.php">
        <input type="text" name="pesquisar" placeholder="pesquisa"><br>
        <input type="submit" value="Pesquisar">
</form>

php.

<?php
     $servidor = "localhost";
     $usuario = "root";
     $senha = "";
     $dbase= "exemplo";

     $conn = mysqli_connect($servidor, $usuario, $senha, $dbase);

1 answer

0


From your send.php file, I assume you already know how to run darlings in PHP. If you don’t know, you can ask here or consult the class mysqli of PHP (which is a good way to connect to Mysql database).

You can use the function LIKE mysql. An example is below.

$query = "SELECT * FROM pessoas WHERE nome LIKE '%".$pesquisar."%'";

Suppose the user has typed Ari in the HTML field. Mysql will search for any name that has substring Ari. Thus, names like MAria, LArissa, MAriana, AriAne, SafAri will appear in the results.


You can perhaps improve your search by searching first for the records whose fields have value equal to the searched, that is, only what is exactly equal to what the user searched; then, what to start with what the user searched; then, what end with what the user searched for; and, finally, what contain what the user searched for.

A way of doing

$pesquisar = $_POST['pesquisar'];
$column = "nome";

$querybase = "SELECT * FROM pessoas WHERE ".$column." "; 
$query = $querybase." = '".$pesquisar."';";        // Os que são idênticos ao pesquisado
$query .= $querybase."LIKE '".$pesquisar."%';";   // Os que começam com o que o usuário pesquisou 
$query .= $querybase."LIKE '%".$pesquisar."';";   // Os que terminam com o que o usuário pesquisou 
$query .= $querybase."LIKE '%".$pesquisar."%' AND ".$column." NOT LIKE '".$pesquisar."%' AND ".$column." NOT LIKE '%".$pesquisar."';";  // Os que possuem o que o que o usuário pesquisou excluindo os que começam e os que terminam (já pesquisados).

Browser other questions tagged

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