cs1h Posted January 30, 2009 Share Posted January 30, 2009 Hi, Does anyone know if there is a simple way to set the initially selected of a drop down list from a value pulled from a database. For example if someone fills out a form saying that there favorite colour is red and they save the form to continue it later. Then when they go back the colour will be set to red as they previously chose. Thanks, Cs1h Quote Link to comment https://forums.phpfreaks.com/topic/143057-solved-drop-down-list-intial-value/ Share on other sites More sharing options...
gevans Posted January 30, 2009 Share Posted January 30, 2009 <?php $colours = array('blue', 'green', 'red', 'yellow'); $choosenColor = 'red'; foreach($colours as $color){ echo '<option name="'.$color.'"'; if($choosenColor == $color){ echo ' selected'; } echo '>'.$color.'</option>'; } Something along those lines Quote Link to comment https://forums.phpfreaks.com/topic/143057-solved-drop-down-list-intial-value/#findComment-750246 Share on other sites More sharing options...
cs1h Posted January 30, 2009 Author Share Posted January 30, 2009 Thanks a lot, that seems to do exactly what I need. Cheers, Cs1h Quote Link to comment https://forums.phpfreaks.com/topic/143057-solved-drop-down-list-intial-value/#findComment-750257 Share on other sites More sharing options...
phpdragon Posted January 30, 2009 Share Posted January 30, 2009 something like this would do it <select name="state" id="state"> <option value='--Please Select--'>--Please Select--</option> <?php include('data_connect.php'); // Define Variables $varname='somevalue'; $defaultvar='defaultvalue' // print state select box $query = "SELECT * FROM table WHERE name='$varname''"; $result = mysql_query($query); while($row_result = mysql_fetch_array($result)) { $variable= $row_result["name"]; if ($variable) { if ($variable!=$defaultvar) { echo "<option value='$variable'>$variable</option>\n"; } } } if ($variable==$defaultvar) { echo "<option value='$variable' selected='selected'>$variable</option>\n"; } ?> </select> You can define the search variable either by another mysql query hard coded or passed to the page either by session url or form. I added the selected option outside the loop as there appears to be a bug in fire fox which fails to load consecutive select options when set inside a loop. Hope this helps. Quote Link to comment https://forums.phpfreaks.com/topic/143057-solved-drop-down-list-intial-value/#findComment-750271 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.