how to make a query that the user can generate?

2

Is there any material to learn?

For example:

I have a pet shop:

Let's say that in my HTML I have several select boxes (animal, breed, sex, age, etc.), in it I can

  • select the dog or
  • select puppy > race or
  • select puppy > race > sex or
  • select puppy > race > age or
  • select puppy > age > sex or
  • etc

    and vice versa for multiple options.

How is a query made for each one of them, and will the choices vary greatly?

select * from nomeTabela WHERE animal='cachorro' AND raca='pintcher'

asked by anonymous 01.07.2015 / 03:42

1 answer

3

I once solved this problem in a search system that had many optional fields.

More or less like this:

$wheres = "";//cria uma string vazia pra receber a clausula where no SQL
$first = true;//variavel pra controlar que é o primeiro campo opcional

//esse $array_busca era simplesmente o $_POST do arquivo.
foreach ($array_busca as $busca) {

    $valor = $busca['valor'];
    $campo_busca = $busca['nome_campo'];

    $where = $campo_busca." = '".$valor."'";
    /*
    Pro caso de haver um campo DATA que precisa ser tratado de um jeito especial. Inclui um tratamento para as datas que estiverem com '/'ao invés de '-'.
       if ($campo_busca == "DATA") {
        $valor = explode(';',$valor);
        $data_ini = implode('-',array_reverse(explode('/',$valor[0]))) ;
        $data_fin = implode('-',array_reverse(explode('/',$valor[1])));

        $where = "(DATA BETWEEN '".$data_ini."' AND '".$data_fin."')";

    }   */  
        if ($first == true) {
                $wheres = $where;
                $first = false;
        } else {
                $wheres = $wheres." AND ".$where;
             }  
        }
if ($wheres != "") {
  $wheres = "WHERE ".$wheres;
} else {
  $wheres = ""; 
}
$query = "SELECT * FROM TABELA ".$wheres." ORDER BY DATA";

It may not be the most efficient, but solved: P

    
01.07.2015 / 04:45