To do a complex search would I have to use OR to combine all instructions?

0

I would like a help to make the SQL according to the data of this figure.

What I know is that if I send AND to all characteristics and one of them returns false or erro all SQL is compromised.

I thought about doing this with OR . Is that correct? But if I do this, one of the features can be ignored, right?

Follow the code I have so far

# Essa variável pega os tipos enviados por $_GET e separá-os.
$tipos  = (@explode('/', implode('/', $_GET['tipo'])));

# Esse foreach pega cada variável e monta a instrução
# **CATEGORIA LIKE '%{$word}% OR**
foreach($tipos as $word){
    $sql[] = "CATEGORIA LIKE '%{$word}%'";
}

# Então SQL pega o resultado do foreach e colocar no WHERE
# e eu termino de ordenar os resultados.
$sql    = 'SELECT * FROM imovel WHERE ' .implode(' OR ', $sql);
$sql   .= ' ORDER BY IMO_CODIGO DESC LIMIT '.$inicio. ', '. $limite;

    
asked by anonymous 06.10.2014 / 18:41

2 answers

4

Mounting a filter


WARNING: Always validate your variables before sending them to the database.

Validating the filter

If the values are standard, use a search instead of a word, so you'll always get consistent results.

$where = 'WHERE 1=1 AND ';

$tipo = Array(
  1, // Apartamento
  2, // Casa
  3  // Terreno
);

if (isset($tipo) && !empty($tipo)){

    // se $tipo for um array e for maior que 0
    if (is_array($tipo) && count($tipo) > 0) {
       $where .= " tipo IN ('".implode("','",$tipo)."') AND ";
    } else {
       $where .= " tipo = '{$tipo}' AND ";
    }

}

$dormitorio = Array(2,3,4); // Quantidade de dormitorios

if (isset($dormitorio) && !empty($dormitorio)){

   if (is_array($dormitorio) && count($dormitorio) > 0){
     $where .= " dormitorio IN ('".implode("', '", $dormitorio)."') AND ";

   } else {
     $where .= " dormitorio = '{$dormitorio}' AND ";
   }
}

I recommend sending the filter via POST , but it can also be done via GET , without problems. Always remember to be cautious against SQL Injection, here you have .

No field informed:

SELECT * FROM imoveis WHERE 1=1

The query will return all the data in the table.

    
06.10.2014 / 19:25
1

You should use and and or separated in blocks with parentheses, for example:

(tipo = apartamento or tipo = casa) and 
(dormitórios = 2 or dormitórios = 3) and 
(vagas = 1 or vagas = 2) and 
(area > 60 and area < 120) and 
(valor > 100000 and valor < 150000)

Sorry for the quality of the answer, I'm on my cell phone, as soon as I can edit and improve ...

    
06.10.2014 / 18:53