2
  <?php
      $sql = "SELECT id, name FROM cities";
      $stmt = $DBcon->prepare($sql);
      $stmt->execute();
      $cities = $stmt->fetchAll();

      $current_city_id = '';

      $current_city_id=$cities[0]['id'];
      $dropdown = '<select name="city">';
      foreach ($cities as $city) {
        $selected='';
        if ($current_city_id==$city['id']) $selected=" selected";

        $dropdown .= '<option value="'.$city['id'].'">' . $city['name'] .'</option>';

      }
      $dropdown .='</select>';
      echo $dropdown;
      ?>

Selected value is not showing in dropdown then user press update button. Can't find where the problem is.

Manu Eidenberger
  • 2,076
  • 1
  • 18
  • 23
  • Seems like you are not printing out _select='selected'_ in the option tag. Take a look at [this answer](https://stackoverflow.com/questions/3518002/how-can-i-set-the-default-value-for-an-html-select-element) on how to set a default selected option in a dropdown. – Manu Eidenberger Nov 10 '17 at 10:07

2 Answers2

2

You are not adding the $selected value in option...

<?php
    $sql = "SELECT id, name FROM cities";
    $stmt = $DBcon->prepare($sql);
    $stmt->execute();
    $cities = $stmt->fetchAll();
    $current_city_id = '';
    $current_city_id=$cities[0]['id'];
    $dropdown = '<select name="city">';
    foreach ($cities as $city) {
        $selected='';
        if ($current_city_id==$city['id']) $selected=" selected";
        $dropdown .= '<option value="'.$city['id'].'" '.$selected.'>' . $city['name'] .'</option>'; //Change Here  
    }
    $dropdown .='</select>';
    echo $dropdown;
?>
GYaN
  • 2,327
  • 4
  • 19
  • 39
1

your are not print out the $selected variable. $selected variable should print in option

 <?php
          $sql = "SELECT id, name FROM cities";
          $stmt = $DBcon->prepare($sql);
          $stmt->execute();
          $cities = $stmt->fetchAll();

            $current_city_id = '';

          $current_city_id=$cities[0]['id'];
          $dropdown = '<select name="city">';
          foreach ($cities as $city) {
            $selected='';
          if ($current_city_id==$city['id']) $selected=" selected";
    //print out selected variable
          $dropdown .= '<option '.$selected.' value="'.$city['id'].'">' . $city['name'] .'</option>';

        }
          $dropdown .='</select>';
          echo $dropdown;
          ?>
Arafath
  • 1,090
  • 3
  • 14
  • 28