How to make a database query with multiple filters

Asked

Viewed 197 times

0

I have this list of filters inserir a descrição da imagem aqui

I can receive all her normal values in an array by get method, but I’m having doubts about how to do this search with several filters, I performed a filter for example search by code, ok worked, but how do I merge all these together? I don’t need you to tell me the code but what would be the step for me to do this search.

1 answer

1


This is a recurring question in developers' minds, but people find it too basic to ask. Congratulations on asking!

I’ll give you some tips:

#1 Submit your search form to the page itself

<form name="busca" action="<? echo $_SERVER['PHP_SELF']; ?>" method="GET">
     <!-- Coloque seus inputs, buttons, selects, etc. aqui dentro -->
</form>

#2 Treat the variables logically in the page header and mount the query as a result of this logical treatment and concatenation of strings resulting.

It’s simpler than it looks, you just need to know how the search should be performed in the database.

Example: Consider only type and category. If category and type are defined the query must be SELECT * FROM minha_tabela WHERE tipo = 'tipo' AND categoria = 'categoria';, if only type is set to query must be SELECT * FROM minha_tabela WHERE tipo = 'tipo'; and so on.

<?php
// Supondo que o nome do botão clicado seja name="botaoBuscar" no formulário
if(isset($_GET["botaoBuscar"])) {
    // Sempre pegando os valores submetidos por GET por meio do nome dos formulários
    $tipo = $_GET["tipo"];
    $categoria = $_GET["categoria"];

    $query = "SELECT * FROM minha_tabela WHERE 1 = 1 "; // Espaço proposital no final

    if(!empty($tipo && isset($tipo) && $tipo !== "")) {
        $query += "AND tipo = " . $tipo;
    }
}

// Conecte-se ao banco de dados e faça sua pesquisa lá.

?>

Of course they are examples, you can submit the form to a separate page and return everything with Javascript asynchronously.

There are countless different methods of doing the same thing and there is the beauty of programming for me. It’s an invitation to think and be more creative in everyday life as programmers.

I recommend using PDO (PHP Data Object).

  • I managed to make the filter work, thank you very much! really was simpler than I imagined.

Browser other questions tagged

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