lovephp Posted June 23, 2016 Share Posted June 23, 2016 ok i made this dropdown which auto populate, but supposing if i store some value in db how on earth i fetch that value matching with my following code? if db value is like year 1999 how do i get it to show in my current dropdown? <select name="reduyear5" required> <option value="" selected="selected" disabled="disabled">Select Passed Year</option> <option value="Persuing">Persuing</option> <?php $start_year = date('Y')-45; $end_year = $start_year+45; for($i=$start_year; $i<=$end_year; $i++){ echo '<option>'.$i.'</option>'; } ?> </select> Quote Link to comment https://forums.phpfreaks.com/topic/301379-keep-dropdown-value-selected-whatever-it-maybe/ Share on other sites More sharing options...
Solution Muddy_Funster Posted June 23, 2016 Solution Share Posted June 23, 2016 You just put a conditional check into the loop as it's constructing the option list (assuming you have already dealt with getting the desired value such as 1999) and set the selected attribute when the loop matches the conditional. for($i=$start_year; $i<=$end_year; $i++){ if ($i == $valueFromDB){ echo "<option value='{$i}' selected='selected'>{$i}</option>"; } else{ echo "<option value='{$i}'>{$i}</option>"; } } you could even use a ternary operator to condense the if/else: ($i == $valueFromDB) ? echo "<option value='{$i}' selected='selected'>{$i}</option>" : echo "<option value='{$i}'>{$i}</option>"; 1 Quote Link to comment https://forums.phpfreaks.com/topic/301379-keep-dropdown-value-selected-whatever-it-maybe/#findComment-1533915 Share on other sites More sharing options...
lovephp Posted June 23, 2016 Author Share Posted June 23, 2016 thanks a ton mate appreciate it. cheers Quote Link to comment https://forums.phpfreaks.com/topic/301379-keep-dropdown-value-selected-whatever-it-maybe/#findComment-1533916 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.