Fahim
Fahim

Reputation: 77

How to get value of option from html select tag using php

 <select name=category>
    <option value='1'>Adventure</option>
    <option value='2'>Drama</option>
 </select>

I want to have the value of selected option. Like if Adventure is selected I want to store 1 or if drama is selected I want to store 2 . How can I do this using php? I have to add this data to a database table where I can't enter the name . I have to add their id . id 1 is for adventure, 2 for drama.

Upvotes: 1

Views: 25063

Answers (2)

Omari Victor Omosa
Omari Victor Omosa

Reputation: 2879

you want something like this

<?php

if (isset($_POST['category']))
{
    $category = $_POST['category'];
    echo "$category";
}
?>

<form method="post" action="" name="form">  
 <select name="category">
    <option value="1">Adventure</option>
    <option value="2">Drama</option>
 </select>
 <input name="submit" type="submit">
</form>

Upvotes: 1

Laurens
Laurens

Reputation: 2607

You would have to wrap it in a form.

<form action="myphppage.php" method="POST">
    <select name=category>
        <option value='1'>Adventure</option>
        <option value='2'>Drama</option>
    </select>
</form

Then on myphppage.php you can get the value from your select by doing:

<?php
if(isset($_POST['category'])) {
    $category = $_POST['category']; // or $_GET['category'] if your form method was GET
}
?>

Upvotes: 0

Related Questions