jpopuk Posted May 15, 2014 Share Posted May 15, 2014 Hi, I have setup a little post function where you can edit it. When the data has been submitted it sends all data to a database. When I go to edit a post this is how I have each dropdown to load the correct option: <select name="ad_type"> <option selected="selected"><?php echo $post['ad_type']; ?></option> <option>-- Please Select --</option> <option value="For Adoption">For Adoption</option> <option value="For Sale">For Sale</option> </select> How would I do it so it would automatically select the correct option rather than having it add another option at the top? Thanks Quote Link to comment Share on other sites More sharing options...
Barand Posted May 15, 2014 Share Posted May 15, 2014 Check which option matched the current value and mark it as selected $opts = array('To let', 'For adoption', 'For sale'); echo "<select name='ad_type>\n<option value = ''>--Please select--</option>\n"; foreach ($opts as $opt) { $sel = $opt == $_POST['ad_type'] ? 'selected="selected"' : ''; echo "<option value='$opt' $sel> $opt</option>\n"; } echo "</select>\n"; Quote Link to comment Share on other sites More sharing options...
jpopuk Posted May 15, 2014 Author Share Posted May 15, 2014 The options are pulled in from a database so the array part would not be the way to go for me. I have tried this: <option value="<?php echo $post['ad_type']; ?>"<?php echo $post['ad_type'] == $post['ad_type'] ? ' selected="selected"' : ''; ?>><?php echo $post['ad_type']; ?></option> But this did not work. Quote Link to comment Share on other sites More sharing options...
Barand Posted May 15, 2014 Share Posted May 15, 2014 Just the same except you loop through returned rows from the query instead of the array elements $sql = "SELECT ad_type FROM mytable"; $res = $db->query($sql); echo "<select name='ad_type>\n<option value = ''>--Please select--</option>\n"; while ($row = $res->fetch_assoc()) { $sel = $row['ad_type'] == $_POST['ad_type'] ? 'selected="selected"' : ''; echo "<option value='{$row['ad_type']}' $sel> {$row['ad_type']}</option>\n"; } echo "</select>\n"; Quote Link to comment 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.