how to create search system using filter

0

I have a search system where I search the users by filtering by: name, age and email. If I filter by name and age and email, everything happens fine, but if I filter only by age, for example, nothing is returned even though I try to bank the correct data. I think I'm doing it the wrong way, because I use the AND operator in the query, that is, I want the three to return true, but that's not quite what I want. I want to filter by: age, or by age and email, or by age and email and name.

<?php 
$nome = addslashes($_GET['nome']);
$idade = addslashes($_GET['idade']);
$email = addslashes($_GET['email']);
    $sql = $pdo->query("SELECT * FROM usuarios WHERE nome = '$nome' AND idade = '$idade' AND email = '$email' ");

?>
    
asked by anonymous 10.09.2017 / 06:01

1 answer

0

I did not find any errors in the code, for me it worked perfectly, what may be happening is that your variable that receives $ _GET of age is not receiving any value, in that case I recommend that you run the code below to check if the variables are receiving values.

<?php 
$nome = addslashes($_GET['nome']);
$idade = addslashes($_GET['idade']);
$email = addslashes($_GET['email']);

//verifica se todos os campos estao recebendo valores
if(!is_null($nome) && !is_null($idade) && !is_null($email)){
    echo "Todos os campos estão enviando valor";
}else{
    echo "Algum campo nao esta correto";
}
?>

Another tip I have for you is to use the PDO in this way to search data in the database, I realize you are using PDO, so you are looking for greater security for your code.

//select de dados de uma forma mais segura
$sql = $pdo->prepare("SELECT nome, idade, email FROM usuarios WHERE nome = :nome AND idade = :idade AND email = :email");
$sql->bindParam(':nome', $nome, PDO::PARAM_STR);
$sql->bindParam(':idade', $nome, PDO::PARAM_INT);
$sql->bindParam(':email', $email, PDO::PARAM_STR);
$sql->execute();
$linha = $sql->fetch(PDO::FETCH_ASSOC);
?>

Anyway, I hope to have helped my friend.

    
10.09.2017 / 07:32