How to send checkbox data to a query with mysql?

6

I do not know how to start this whole process of sending multiple data to a query in the database. I always submit an item for each types but never submitted multiple items of the same type . The image below will best illustrate:

IwouldlikeyoutohelpmewithconceptssothatIcanachievethedesiredresult.Iguessit'sallaboutcapturingvaluesandstoringthevariablesinarraysbutIdonotknowmuchmorethanthat.

Forlogic,IthinkIwouldselectrealestatefromallcitiespresented,thentypeofpropertyandthenamountofdorms,atleastIthinkitwouldbeso.IwouldliketoknowthewholeprocessfromHTMLtoquery.

Modification:Iputthisurl link what I have done so far. I made HTML of the three results that I have to capture with PHP in the form of array .

</body> 
    <form> 
        <p>Selecione a cidade: </p> 
        <input type="checkbox" name="cidade[]" value="Campo Grande">Campo Grande<br> 
        <input type="checkbox" name="cidade[]" value="Dourados">Dourados<br> 
        <input type="checkbox" name="cidade[]" value="Três Lagoas">Três Lagoas<br> 
        <input type="checkbox" name="cidade[]" value="Corumbá">Corumbá<br> 
        <input type="checkbox" name="cidade[]" value="Naviraí">Naviraí<br> 
        <input type="checkbox" name="cidade[]" value="Paranaíba">Paranaíba<br> 
        <input type="checkbox" name="cidade[]" value="Aquidauana">Aquidauana<br><br>         

        <p>Tipo de imóvel: </p> 
        <input type="checkbox" name="imovel[]" value="Apartamento">Apartamento<br> 
        <input type="checkbox" name="imovel[]" value="Casa">Casa<br> 
        <input type="checkbox" name="imovel[]" value="Comercial">Comercial<br> 
        <input type="checkbox" name="imovel[]" value="Terreno">Terreno<br> 
        <input type="checkbox" name="imovel[]" value="Condomínio">Condomínio<br><br> 

        <p>Selecione a quantidade de dormitórios: </p> 
        <input type="checkbox" name="dormitorios[]" value="1 Dormitório">1 Dormitório<br> 
        <input type="checkbox" name="dormitorios[]" value="2 Dormitórios">2 Dormitórios<br> 
        <input type="checkbox" name="dormitorios[]" value="3 Dormitórios">3 Dormitórios<br> 
        <input type="checkbox" name="dormitorios[]" value="4 Dormitórios">4 Dormitórios<br> 
        <input type="checkbox" name="dormitorios[]" value="5 Dormitórios">5 Dormitórios<br> 
    </form> 
    
asked by anonymous 03.09.2014 / 14:54

2 answers

4

If you plan to do some as a SELECT, you could use the IN, based on the array obtained. You could do this:

    $parseInQuery = function(array $array){
        return ''' . implode('','', $array) . ''';
    };

    // Condições para execução da consulta

    $queryData = $parseInQuery($_POST['cidade']);
    echo $query = "SELECT *  FROM tabela WHERE nome IN($queryData)";

   // imprime: SELECT * FROM tabela WHERE nome IN('Campo Grande','Minas Gerais')

In this case I used an anonymous function to create a function inside $ parseInQuery, to convert the Array to the selected elements in an "In" of MYSQL.

That would also work:

if (!empty($_POST['cidade'])) {
    $queryData = ''' . implode('','', $_POST['cidade']) . ''';
}

Update:

Given the need for multiple data in this query, I wrote the following form, which has the security of filter_input

function parseMysqlQuery($array)
{
    $output = '';

    foreach( $array as $key => $value){
       $output .= !$output ? " WHERE $key " : " AND $key ";
       $output .= 'IN('' . implode('','', $value) . '')';
    }

    return $output;

}
$array = (array)filter_input_array(INPUT_POST, array(
    'cidade' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags'  => FILTER_FORCE_ARRAY,
    ),
    'imovel' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags'  => FILTER_FORCE_ARRAY,
    ),

    'dormitorios' => array(
        'filter' => FILTER_SANITIZE_STRING,
        'flags'  => FILTER_FORCE_ARRAY,
    ),
));


if ($_SERVER['REQUEST_METHOD'] == "POST") {
    $array = array_filter($array);

    $in = parseMysqlQuery($array);

    $query = "SELECT * FROM tabela " . $in;

    // SELECT * FROM tabela WHERE bairro IN('Ibirité') AND dormitorios IN('1 quarto')

    echo $query;
}
    
03.09.2014 / 16:37
2

You have two steps to solve:

  • Access request data
  • Mount the SQL query
  • I'll give quick answers that can guide you.

    To access the data already commented above you simple your $_POST['cidades'] and already has an array with the cities. Simple

    To mount the query and filter on the database you will use Join, In, and Where. Example:

    select i.nome from imovel i join cidade c where c.nome in ("Campo Grande","Paranaíba") and i.tipo in ("Casa","Apartamento") and i.dormitorio in ("4","5")
    

    To mount a query like this, you "can" do in PHP concatenation of strings, this will open your application for SQL Injection a serious security flaw, but the alternative is a long story and will depend on how you are building the app. Suggested use Doctrine 2 for data access

    With regard to example query the name of the city is not a good practice, ideally it is to have an id like number representing the city your form would look like

    <input type="checkbox" name="cidade[]" value="1672">Aquidauana<br><br>
    

    Notice that value is now a number that represents the primary key in the database. The same applies to the type of property, in the example I considered it is in the same table, but in practice it is better to have a separate table and join the 3. Since this follows standardization practices and the independent type of property can vary and be changed (if someone registers a type with wrong name and change it after the application has already saved real estate will give problem)

        
    03.09.2014 / 17:17