0
This code must return all records from the table immovable if the array is empty and returns selected records if there are items in the array.
I can have the array mounted and the database consulted if I select at least one form item but cannot return all the values of the database if the array is empty. In fact it does not arrive empty, it arrives like this: [0] =>
and that’s the part that makes a mistake.
# 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 immovable WHERE 1=1 AND CATEGORY IN ('')
SQL with array items:
SELECT * FROM immovable WHERE 1=1 AND CATEGORY IN ('CASA')
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>
The problem with this code is that even though I don’t select any item and send the form with array theoretically empty it commits SQL by adding
AND CATEGORIA IN ('')
because actually the array is not empty but has 1 empty index.– Marcos Vinicius
Mark avoid this kind of gambiarras of
WHERE 1=1
and create your dynamically shaped querys. Also eliminate this explode with error suppression (@
).– gmsantos
What is the purpose of the implode/explode line? php already transforms its input into array without having to do so ai: http://phpfiddle.org/main/code/n0kp-9hmf
– gmsantos
It has indexes that arrive alone but it has indexes that arrive
APARTAMENTO/APTO DUPLEX
and I need to send these terms individually, break them up in the / (bar).– Marcos Vinicius
It wouldn’t be the case if you split your form into two fields?
APARTAMENTO
andAPTO DUPLEX
?– gmsantos
For reasons of layout it is no longer possible to implement this solution, it follows image: http://puu.sh/c2vtG/0348a1ad0f.png ... no space for more fields and they want to send 2 properties by input.
– Marcos Vinicius
You say you always create the query with
IN ('')
even without informing any field?– Papa Charlie
In this case, how the query creates an empty index
[0] =>
in the form Ubmit, the statementcount($tipo) > 0
is TRUE and if it is TRUE he addsAND CATEGORIA IN ('')
in SQL.– Marcos Vinicius