简体   繁体   中英

display saved data in dropdown list when reopen the page in php and mysql

Is it possible to display saved values in dropdown from mysql to php when i login again? My codes saves the value in Mysql. But when i login back, it displays blanks field (which is default in dropdown list)

$sql = "SELECT Program_Description FROM programs";
$result = mysqli_query($dbc, $sql);
$dropdown = "<select name='Program_Description'>";
$dropdown .= "<option value= ></option>";
while($row = mysqli_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['Program_Description']}'>{$row ['Program_Description']}     </option>";
}
$dropdowna .= "\r\n</select>";

Try this,

    $sql = "SELECT Program_Description FROM programs";
$result = mysqli_query($dbc, $sql);
$savedValueInDb = ""; //fetch the DB saved value and assign to this variable
$dropdown = "<select name='Program_Description'>";
$dropdown .= "<option value= ></option>";
while($row = mysqli_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['Program_Description']}'";
$dropdown .= ($savedValueInDb == $row ['Program_Description']) ? " selected " : "";
$dropdown .= ">{$row ['Program_Description']}     </option>";
}
$dropdowna .= "\r\n</select>";

Do this

 //Suppose the $selecteValue contains the selected value which you have fetched from the database
 $selectedValue = 'test';

 $sql = "SELECT Program_Description FROM programs";
 $result = mysqli_query($dbc, $sql);
 $dropdown = "<select name='Program_Description'>";
 $dropdown .= "<option value= ></option>";
 while($row = mysqli_fetch_assoc($result)) {
      $dropdown .= "\r\n<option ".(($selectedValue == $row['Program_Description']) ? ' selected ' : '')." value='{$row['Program_Description']}'>{$row['Program_Description']}     </option>";
 }
 $dropdowna .= "\r\n</select>";

Another solution would be to

   $sql = "SELECT Program_Description FROM programs";
   $result = mysqli_query($dbc, $sql);
   $dropdown = "<select name='Program_Description'>";
   $dropdown .= "<option value= ></option>";
   $strSelect = '';
   while($row = mysqli_fetch_assoc($result)) {
         if ($selectedValue == $row['Program_Description']) {   $strSelect = ' selected '; } else { $strSelect =  ''; }
        $dropdown .= "\r\n<option ".$strSelect." value='{$row['Program_Description']}'>{$row['Program_Description']}     </option>";
   }
   $dropdowna .= "\r\n</select>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM