Search code examples
phpdropdown

Not getting desired value from dropdown PHP


I am trying to update the page to show the selected country after the user chooses a value from a list of countries in the dropdown. When i try to echo $selected_country, the value is "". For some reason, when the form submits the value is not being updated. Can anyone help please?

<div class="row pt-4 pb-4">
            <div class="col-4">
                <h2 class="table_title">Travel Restrictions</h2>
                <p class="table_title">
                    See what countries you can travel to.
                    <?php if (isset($_POST['submit_dropdown'])) {
                                $selected_country = $_POST['submit_dropdown'];
                                echo $selected_country;
                    }
                      ?>
                </p>
            </div>

            <div <?php echo $css_tag_dropdown ?>>
                <div class="text-center">
                    <p class="table_title">
                        Select the originating country.
                    </p>
                    <form method="post">
                        <select class="form-control" name="submit_dropdown" onchange="this.form.submit();">
                            <option selected>Select country</option>
                            <?php while ($row = mysqli_fetch_array($dropdown_origins)) :; ?><option value=""><?php echo $row[0]; ?></option><?php endwhile; ?>
                        </select>
                    </form>
                </div>
                <div class="col"></div>
            </div>
        </div>

Solution

  • $_POST['submit_dropdown'] holds the value attribute of the selected option, so you should populate that in your while loop according to the country:

    <option value="<?php echo "$row[0] country code here"; ?>"><?php echo $row[0]; ?></option>