How to use checkbox group to do search with php and mysql

0

I'm developing a real estate site with a search, where one of the filters is the neighborhood. Currently it's a dropbox, but I'd like to switch to a checkbox group so I can select more than 1 neighborhood at a time, how can I do that?

I thought of some way to send the information something like this: (& neighborhoods = centro, tatuape)

The search is done with $ _GET.

Form:
<form id="buscalancamento" name="nomebuscalancamento" method="get" action="/incorporadora/terrenos">
<select type="text" name="bairro">
<option>Todos</option>
<option>Centro</option>
<option>Tatuape</option>
</select>
<button type="submit"">Buscar</button>
</form>

And the query:

$bairro = $_GET['bairro'];
//FILTRO BAIRRO
if (isset($bairro)) {
    if($bairro=='Todos'){
        $wbairro='';
    }else{
        $wbairro=' AND bairro LIKE "'.$bairro.'" ';
    }
}else{$wbairro='';}
$query=("SELECT *, FROM #__ter_terrenos WHERE id > 0".$wbairro);
$db -> setQuery($query);

I do not know how to send all the chebkox with the values together, nor do the query with this data sent

    
asked by anonymous 23.07.2018 / 16:14

3 answers

1

(excuse my Portuguese but I'm not native)

You need to use several checkboxes with the same name, so that in the php file the data can be received as an array. Soon you implode the data and you can use Mysql IN. Example:

No HTML :

<form id="buscalancamento" name="nomebuscalancamento" method="get" action="revision_mg.php">
<input type="checkbox" name="bairro[]" value="Todos">
<input type="checkbox" name="bairro[]" value="bairro1">
<input type="checkbox" name="bairro[]" value="bairro2">
<input type="checkbox" name="bairro[]" value="bairro3">
<input type="checkbox" name="bairro[]" value="bairro4">
<button type="submit">Buscar</button>
</form>

No PHP :

<?php
$wbairro = "";
//FILTRO BAIRRO
if (isset($_GET['bairro'])) {//melhor fazer validação aqui e logo alocar a variável
    $bairro = $_GET['bairro'];
    if(in_array("Todos", $bairro)){
        $wbairro='';
    }else{
        $wbairro = " AND bairro IN(";
        $wbairro .= "'" . implode("','", $bairro) . "'";
        $wbairro .= ")";
        }
}else{$wbairro='';}


$query=("SELECT *, FROM #__ter_terrenos WHERE id > 0".$wbairro);
$db -> setQuery($query);
?>

As you need a cleaner url, I did the following, but the code is a bit more complex. I use javaScript to adapt the URL: so when you click on it it sends the data to a javascript function, and it creates an array with the values you select, if you delete a check then it removes the value from the array . When you click on fetch, then again it is called a javascript function that takes the values from the array, allocates the input hidden and sends it to the url:

HTML:

<form id="buscalancamento" name="nomebuscalancamento" method="get" action="revision_mg.php">
<input type="checkbox" id="Todos" onChange="alocar('Todos')">
<input type="checkbox" id="barrio1" onChange="alocar('barrio1')">
<input type="checkbox" id="barrio2" onChange="alocar('barrio2')">
<input type="checkbox" id="barrio3" onChange="alocar('barrio3')">
<input type="checkbox" id="barrio4" onChange="alocar('barrio4')">
<input type="hidden" id="bairros" name="bairros" value="">
<button type="button" onClick="send()">Buscar</button>
</form>

JavaScript

<script>
    var bar = Array();
    var barrios = document.getElementById("bairros");
function alocar(valor){//Pega o valor do check

    if(document.getElementById(valor).checked == true){//Se ta ligado agrega o valor
        bar.push(valor);        
    }else{//Se desliga apaga o valor do array
        let index = bar.indexOf(valor);
    if (index !== -1) bar.splice(index, 1);
    }
}

function send(){
    var juntar = "";
    let cant = bar.length;
    //Criar um string com o dados do array
    for(i = 0; i < cant - 1; i++){
        juntar = juntar + bar[i] + "_";
    }

    //Deixa o ultimo elemento fora para evitar um _ demais ao final do String
    juntar = juntar + bar[cant -1];

    barrios.value = juntar;
    document.getElementById("buscalancamento").submit();
}
</script>

PHP

$wbairro = "";
//FILTRO BAIRRO
if (isset($_GET['bairros'])) {
    $bairro = $_GET['bairros'];
    if(strpos($bairro, "Todos") !== false){
        $wbairro='';
    }else{
              $wbairro = " AND bairro IN(";
        $wbairro .= "'" . str_replace("_", "','", $bairro) . "'";
              $wbairro .= ")";

        }
}else{$wbairro='';}

$query=("SELECT *, FROM #__ter_terrenos WHERE id > 0".$wbairro);
$db -> setQuery($query);

Hope I can help you

    
23.07.2018 / 17:14
0

My answer uses the principle similar to that of @JoseMelendez, but with a slightly different programming and, in my opinion, more simplified.

Create a input hidden after the checkbox , by setting the .bairro class to checkbox , except for "Everyone", and name="bairro" only in input hidden, as below: p>

<input type="checkbox" value="centro" class="bairro"> centro
<input type="checkbox" value="tatuape" class="bairro"> tatuape
<input type="checkbox" value="Todos"> todos
<input type="hidden" name="bairro">

Create a onsubmit event by JavaScript that will insert in input hidden value to be sent, under the following conditions:

  • If no% of% is checked, it will be considered "All";
  • If% "Everyone" is checked, it will have priority, even if you have marked others.

JavaScript:

var form = document.forms[0];
form.onsubmit = function(){

   var bairros = document.querySelectorAll(".bairro:not([value='Todos']):checked");
   var bairro = '';
   for(var x=0; x<bairros.length; x++){
      bairro += bairros[x].value+',';
   }

   bairro = bairro.substring(0, bairro.lastIndexOf(","));
   form.bairro.value = document.querySelector("[value='Todos']:checked") || !bairro ? "Todos" : bairro;

}

In PHP you will make a checkbox converting the variable checkbox to array and making a explode will build the query $bairro :

$bairro = $_GET['bairro'];
//FILTRO BAIRRO
if (isset($bairro)) {
    if($bairro=='Todos'){
        $wbairro='';
    }else{
      $bairro = explode(",", $bairro );
      foreach($bairro as $item){
         $consulta .= '"'.$item.'",';
      }
      $wbairro = ' AND bairro IN('.rtrim($consulta, ",").')';
    }
}else{$wbairro='';}
$query=("SELECT *, FROM #__ter_terrenos WHERE id > 0".$wbairro);
$db -> setQuery($query);

The result of foreach will set IN() to values like this:

AND bairro IN("centro","tatuape")

The foreach function will only return the records that have the term in the parameters.

The result of GET in the URL will look like this:

/incorporadora/terrenos?bairro=centro%2Ctatuape

Where the code IN() represents a comma.

    
23.07.2018 / 17:24
0

Follow the code as I commented I would be doing. It will generate a URL so="neighborhoods = neighborhood1% 2Cbairro2% 2Cbairro3" HTML:

<form action="" method="GET" id="pesquisa">
    <input type="hidden" name="bairros" id="bairros" value="">
    <input type="checkbox" value="bairro1" data-name="bairro" checked>bairro1
    <input type="checkbox" value="bairro2" data-name="bairro">bairro2
    <input type="checkbox" value="bairro3" data-name="bairro">bairro3

    <button type="submit">enviar</button>
</form>

JS (Jquery):

$(document).on('submit','#pesquisa',function(e){
    var bairros = '';

    $('input[type="checkbox"][data-name="bairro"]:checked').each(function( index ) {
        bairros = bairros + $(this).val()+',';
    });
    bairros = bairros.substring(0,bairros.length - 1);
    $('#bairros').val(bairros);
});
    
23.07.2018 / 19:47