Rewrite the code to display expected result?

0

This code should return all records in the property table if the array is empty and return selected records if there are items in the array.

I can get the array to be mounted and the database queried if I select at least one form item but I can not return all the values in the database if the array arrives empty. In fact it does not arrive empty, it arrives like this: [0] => and it is that part that gives error.

# Selecionando o tipo de imóvel
$tipo = $_POST['tipo'];
$tipo = (@explode('/', implode('/', $tipo)));

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

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

SQL without array items:

  

SELECT * FROM property WHERE 1 = 1 AND CATEGORY IN ('')

SQL with array items:

  

SELECT * FROM property WHERE 1 = 1 AND CATEGORY IN ('HOME')

Form

<input type="checkbox" name="tipo[]" value="CONJUNTOSALA/LOJA" id="tp5">
<label for="tp5">Conjunto/Sala/Loja</label>

<input type="checkbox" name="tipo[]" value="FLAT/LOFT" id="tp6">
<label for="tp6">Flat/Loft</label>

<input type="checkbox" name="tipo[]" value="PREDIO COMERCIAL" id="tp7">
<label for="tp7">Prédio Comercial</label>

<input type="checkbox" name="tipo[]" value="TERRENOS" id="tp8">
<label for="tp8">Terreno/Área</label>
    
asked by anonymous 07.10.2014 / 04:28

1 answer

2

Your variable has an empty index because you are giving explode . And there is no need for this explode . So you can do this:

# Selecionando o tipo de imóvel
if (isset($_POST['tipo']) && is_array($_POST['tipo']) && count($_POST['tipo']) > 0){
   $where .= " CATEGORIA IN ('".implode("','", $_POST['tipo'])."') AND ";
}

According to your form, your variable $_POST['tipo'] will always be an array .

Note: It is not recommended to send data to the bank without treatment. That is, research on security and handling of variables before concatenating them with your Query SQL .

    
07.10.2014 / 13:38