How to use checkbox group to search with php and mysql

Asked

Viewed 1,387 times

0

I’m developing an immovable site with a search, where one of the filters is the neighborhood. Currently it is a Dropbox, but I would like to swap by checkbox group to be able to select more than 1 neighborhood at a time, how can I do this?

I thought of some way to send the information more or less like this: (&neighborhoods=center,)

The search is done with the $_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 consultation:

$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 don’t know how to send all chebkox with values together, nor do query with this data sent

  • Ever tried to exchange LIKE for IN? Since neighborhoods are generated by a select and not informed by the user would not need to use LIKE...

  • About using the values sent, they will be sent as array per post or get if post only uses a var_dump($_POST['fieldname']); to check what is coming, then use an IMPLODE to join the array.

  • You can also convert Dropbox to Multiple where the user can select several items. Just add multiple: <select multiple>

  • @Lucasgauna I will test with the IN, but how do I send the get all selected checkbox together?

  • @sam thought about it, but the customer wanted to checkbox even, by clicking select neighborhood he appears a checkbox group

  • @Leandromarzullo, practically you will have to do it : "'". implode(" ',' ", $array)."'";

  • @Leandromarzullo instead of the array you use your checkbox set, remember that their name should be correct, which would be name="checkbox[]". Give a test and return the result here. The most important thing is to var_dump the checkbox field and check whether it’s coming as an array or not.

  • ve se entendi, in place of select, I will put something like this: <input type="checkbox" name="checkbox[]" value="Center"> <input type="checkbox" name="checkbox[]" value="Tattooing">? if it is, I did then it appeared on get: checkbox%5B%5D=Centro&checkbox%5B%5D=Tatuape

  • @Leandromarzullo I will be performing some tests please wait a minute, I will be putting as answer

  • @Leandromarzullo, you use Jquery?

  • @Lucasgauna, I can use

Show 6 more comments

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 into the data and can use Mysql IN. Example:

In 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>

In 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);
?>

Since Voce needs a cleaner url, I did the following, but the code is a bit more complex. Use Avascript to adapt the URL: so when you click under the check 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 quits the value of the array. When you click on search, then again it is called a javascript function that takes the values of the array, allocates to the Hidden input and sends by 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);

I hope I can help you

  • worked, but the url was neighborhoods%5B%5D=bairro1&neighborhoods%5B%5D=bairro2, it has something like this: neighborhoods=bairro1,bairro2 or any other character in place of the comma, to keep repeating the neighborhoods%5B%5D= and stay a very big link

  • The method has to be GET? because you can use method POST, so the data goes in the form body and not in the url

  • has to be get, because the customer wants to be able to apply the filter and compare the link with the filter he made

  • I got what you need, I’ll update my answer

  • The code I was supposed to send does the same thing as @Josemelendez’s, I consider his answer correct, but I’ll be providing my code anyway.

0

My answer uses the principle similar to @Josemelendez’s, but with a slightly different and, in my opinion, more simplified programming.

Create a input hidden after the checkbox, putting the class .bairro us checkbox, except for the "All", and name="bairro" only in the input hidden, as below:

<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 an event onsubmit by the Javascript you will insert into input occult the value to be sent, under the following conditions:

  • If any checkbox is marked, will be considered "All";
  • if the checkbox "All" is marked, he will have priority, even though he has 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 explode converting the variable $bairro array and making a foreach will build the query IN():

$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 mount the IN() with the values in this way:

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

The function IN() will return only records that have the term in the parameters.

The GET output in the URL will be something like:

/incorporadora/terrenos?bairro=centro%2Ctatuape

Where the code %2C represents a comma.

0

It’s code like I said it would be. A URL will be generated like this = "neighborhoods=bairro1%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);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.