Adam Short
Adam Short

Reputation: 498

Get ID of php populated select option

I populate an HTML Select drop down using data from a MySQL table. What I need to do is fetch the ID of that option and submit it to a different table, but have no clue how to do it. Here's how it's populated:

$query = $mysqli->query("SELECT RaceName FROM Race ORDER BY RaceName"); 
                ?>
<select class="pure-input-2" required="required" name="raceName">
    <option value="" disabled="disabled" selected>Select a race</option>
        <?php while($option = $query->fetch_object()){ ?>
            <option><?php echo $option->RaceName; ?></option>
        <?php } ?>
    </select>

How can I then retrieve the ID of the selected option to submit to a different table?

I guess in the SELECT query I could also select the RaceID, but how can I then pass this through the submit button?

Thanks.

Upvotes: 0

Views: 87

Answers (1)

vusan
vusan

Reputation: 5331

Like this:

$query = $mysqli->query("SELECT RaceID, RaceName FROM Race ORDER BY RaceName"); 
                ?>
<select class="pure-input-2" required="required" name="raceId">
    <option value="" disabled="disabled" selected>Select a race</option>
        <?php while($option = $query->fetch_object()){ ?>
            <option value="<?php echo $option->RaceID; ?>"><?php echo $option->RaceName; ?></option>
        <?php } ?>
</select>

So the value of $_POST['raceId'] will be the option value ie.RaceId.

Upvotes: 1

Related Questions