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

Asked

Viewed 901 times

0

I have a search with a select that can select more than one option, but I don’t know how to make them search all the selected options.

Currently it does the search, inserts the values in the url (I am using GET), but can’t do the 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 consultation:

$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 hence the $_GET only takes 1 neighborhood, how do I use all to return to the query?

Thank you!

2 answers

2


Change the name of select that way:

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

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

1

The first point is that a select with multiple options, will always send a array. Then, 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 consultation is vulnerable to SQL Injection. Therefore, the example will be using PDO.

By example, consulting using the operator = and not like, the easiest way to query multiple records, is by using the operator IN

To be safe, you must use preparad statements. However, PDO does not have query support IN via prepared statements.

To solve this, you will have to create the SQL string according to the amount 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 this is done, you will get a query using multiple parameters from a single select.

Browser other questions tagged

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