How to use multiple select in PHP form to query in MYSQL

0

I have a search with a select that can select more than one option, but I do not know how to do it so they search for all the selected options.

Currently it does the search, it inserts the values in the url (I'm using GET ), but it can not do SELECT of all values. Below the code snippet:

<form method="get">
<select name="bairro">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
</form>

and the query:

$bairro = $_GET['bairro'];
$query=("SELECT * FROM terrenos WHERE bairro = '".$bairro."'"};

If I select A and B for example, the URL is &bairro=A&bairro=B , but then $_GET only takes 1 neighborhood, how do I use all to return to the query?

Thank you!

    
asked by anonymous 03.08.2018 / 14:51

2 answers

2

Change name of select like this:

<input ... name="bairro[]" ... >

This way you will get $_GET["bairro"] as an array with form data.

    
03.08.2018 / 15:02
1

The first point is that a select with multiple options will always send a array . So you should treat it as such. However, the name should be treated as an array ( name="bairro[]" ).

<form method="get">    
    <select name="bairro[]">
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>    
</form>

The second point is that your query is vulnerable to SQL injection . Therefore, the example will be using PDO .

According to your example, querying using the = operator and not like , the easiest way to query multiple records is by using the IN

To be safe, you should use prepard statements . However, PDO does not support query IN via prepared statements .

To solve this, you will have to create the SQL string according to the number of parameters:

$paramtersQty = count($_GET['bairro']); //Retorna a quantidade de parâmetros
$markedPlaceholders = array_fill(0 , $paramtersQty , '?'); //Cria um array com placeholders para a query
$markedPlaceholders = implode(',' , $markedPlaceholders); //transforma os placeholders em uma única string.

//cria o statement
$statement = $pdo->prepare('SELECT * FROM terrenos WHERE bairro ('.$markedPlaceholders.');');

//passa todos os argumentos como parâmetros para a consulta.
$statement->execute($_GET['bairro']);

Once you have done this, you will have a query using multiple parameters from a single select .

    
03.08.2018 / 15:02