Home > Enterprise >  Update Selected Option in Select based on PHP query
Update Selected Option in Select based on PHP query

Time:11-08

Im trying to update a drop down list with the countries of the world from a db query, which is working fine. I want to set the country of the user as selected, based on their IP. I am collecting their IP fine and working out their country, but Im struggling to set the selected in the output based on this.

<?php
include_once 'database.php';
$result = mysqli_query($conn,"SELECT *
  FROM tbl_fm_countries
  order by Country Asc");


$ipcountry = "United Kingdom";
?>



<form action="results.php" method="post" id="foodmilesTracker">
  <fieldset>
  <legend>Where are you?</legend>
    <ol>
      <li>
      <label for="countryTo">Your Location</label>
      <select name="countryTo">
      <?php
      // output data of each row
        while($row = $result->fetch_assoc()){ 
        echo "<option value='" . $row['CountryId'] . "'>" . $row['Country'] . "</option>";

      }
      ?>

       </select>
       </li>    
    </ol>
</fieldset>

I have tried lots of options and seem to get all set as selected or none. For the example I am setting ipcountry manually.

CodePudding user response:

I recommend doing it following way

<?php while($row = $result->fetch_assoc()){ ?>

<option value="<?php echo $row['CountryId']; ?>" <?php echo $row['Country'] == $ipcountry ? 'selected':''; ?>><?php echo $row['Country']; ?></option>

<?php } ?>
  • Related