Phone book with database

Asked

Viewed 664 times

1

I have a phone book with the form already ready and now I need that when the user type in the field search a name or sector, this value should be compared with values of the database and be returned a value that corresponds to his search.

Follow my PHP code so far;

$bdServidor = '';
$bdUsuario = '';
$bdsenha = '';
$bdBanco = 'lista_telefonica';

$conexao = mysqli_connect($bdServidor, $bdUsuario, $bdsenha,$bdBanco);

if(mysqli_connect_errno($conexao))
{
    echo"problemas para conectar no banco.Verifique os dados!";
    die();
}

// Variavel que contem o valor do campo BUSCA;
$valor = $_POST['busca'];
  • Welcome to stackoverflow in English! Next time try explaining your question and what you want. Have you tried anything? If yes show your code and describe where the problem is.

2 answers

3


To do this you will need to do a survey (SELECT) in the Database and use the LIKE to check if there is a word in that field.

$sql = "SELECT id, name FROM lista_telefonica WHERE nome LIKE '%$valor%' OR setor LIKE '%$valor%"; 

if ($result = query($conexao, $sql)) 
{
    while($obj = $result->fetch_object())
    {
        $line =$obj->id;
        $line.=$obj->name;
    }
}
$result->close();
unset($obj);
unset($sql);
unset($query); 

PS: Don’t forget to use Prepared Statements because of the SQL INJECTION

  • 1

    Thanks for the help.. I will study your code and about LIKE and then increment in my program;

  • You’re welcome. What I did was a minimalist version of how it’s done, anyway you’ve got all the information you need to learn, anything, ask a question.

1

You should use a query SELECT something like that:

<?php
 $consulta=$ pdo->query("SELECT nome, usuario FROM login;");

 while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) 
{ echo "Nome: {$linha['nome']}
 - Usuário: {$linha['usuario']}
<br />"; } ?>

Look for more on CRUD, it’s something simple to do that yours SELECT. How much to compare you should use in SELECT a verifier, such as a '%LIKE' of SQL.

Here is an example about CRUD

Ah remembering that in your form you have to get the variable.

Follow the steps of this tutorial above and find out about the LIKE.

  • He’s using mysqli. And it wasn’t the mustache that asked the question.

  • 1

    OK @Jorgeb. Regardless of the database it will have the LIKE as well explained below and quoted above :)

Browser other questions tagged

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