Nexus9988
Nexus9988

Reputation: 79

Select/Option Value into SQL

I'm what im trying to accomplish is have a select form element with pre-defined options

<select name="select1">
   <option value="value1">Value 1</option>
   <option value="value2">Value 2</option>
   <option value="value3">Value 3</option>
</select>

my sql is the following

$OptionValue = $_POST['select1'];

is that how i should grab the value of the selected option from a form and put it into a php variable to be queried?

Upvotes: 0

Views: 9051

Answers (3)

Nemeth
Nemeth

Reputation: 166

First step is prevent SQL injections with prepared statements. Example: Prepared Statements

Use this to put your selected option into query: $mySelectedOption = $_POST['select1']; $query = "SELECT column_name FROM table_name WHERE column_name = '{$mySelectedOption}'";

Upvotes: 0

Luka
Luka

Reputation: 1718

Use $optionValue = mysqli_real_escape_string ($connection , $_POST['select1']) before executing the query to prevent the most of SQL injections.

Upvotes: 0

Ethan
Ethan

Reputation: 2784

You need to make sure that you are filtering your user input to prevent against sql injection. This alone is quite insecure.

Make sure that you are using either PDO or MySQLi. And if not using prepared statements, your user input needs to be escaped.

See here.

Essentially you have it right though.

Edit:

From the client side I could easily change it to:

<select name="select1">
   <option value="value1">Value 1</option>
   <option value="';DROP TABLE users">Value 2</option>
   <option value="value3">Value 3</option>
</select>

or similar... and now you're screwed if you haven't escaped your input.

Upvotes: 1

Related Questions