Luis
Luis

Reputation: 3277

Insert an option from drop list to database

I have this drop list for example:

<p>Your Age:</p>
<select>
    <option value="1">0 - 13</option>
    <option value="2">13+</option>
    <option value="3">18+</option>
</select>

WHAT I'M DOING NOW is to take the value (1, 2, 3..) and insert it to the users table in the column age, how do I know which value belongs to age? I have a table ages with id and the age.

I'm not sure this way necessary, it's too much complicated and not effectively I think.

The other option is to take a string with the age and just put it in the column age, but this way is less dynamically and in what way I can check if the string is one from the ages?

What do you say? Thank you.

Upvotes: 0

Views: 571

Answers (4)

Dhruvisha
Dhruvisha

Reputation: 2530

you need to give select box "name" attribute by which you can take values of select box from name attribute.

<select name="ages">
<option value="1">0 - 13</option>
<option value="2">13+</option>
<option value="3">18+</option>

When you click on submit ,in code just write

$age = $_POST['ages'];

You will get value of selected age from select box.

Upvotes: 0

Dusean Singh
Dusean Singh

Reputation: 1484

I think you can create a attribute in the table with enum(1,2,3) and afterwards you can send value of 1, 2 or 3 to the table.

Advantages: You don´t need to save the ages in database just (1, 2, 3), You don´t need to save a extra table for ages, which is also a way (Creating a table of three ages and then relating one row in age column).

Disadvantag: Extra code (Maybe), depeding on how often you call it and how object-oriented you application is.

You can just check what ages is with a if & else and save it a global variable.

Upvotes: -1

elkaz
elkaz

Reputation: 310

You can either set the value of the option to match the value between the option tag when you generate the select field or you can have a look up array when you submit it - something like

$ageMap = array(
    "1" => "0 - 13",
    "2" => "13+",
    "3" => "18+"
);

// get the value using the posted value from your select field
$ageMap[$_POST["YourAge"]];

Upvotes: 2

benedict_w
benedict_w

Reputation: 3598

You need to give your select a name attribute, and then you can retrieve if from the $_POST variable in PHP, e.g.

<form action="your_php_page.php" method="post">
    <select name="age">
        ... 
   </select>
</form>

Then in PHP use:

$_POST['age']

Upvotes: 1

Related Questions