0

Hello I have a dropdown menu which holds items from my database when the submit button is pressed the menu item is not retained instead it resets back to what it started initially.

I read a couple of posts about the subject but my case is specific I am not sure where I should insert the selected attribute.

<form name="upServForm"  action="" method="post" >

<?php
        $dropdown = "<select name='codes'>";
        while($row = mysql_fetch_assoc($result2)) 
        {
            $dropdown .= "\r\n<option value='{$row['sid']}'>{$row['sid']}</option>";
        }
        $dropdown .= "\r\n</select>";
?>
0

1 Answer 1

0

try this:

$dropdown = "<select name='codes'>";
while($row = mysql_fetch_assoc($result2)) 
{
    $dropdown .= "\r\n<option value='{$row['sid']}'".(($_POST["codes"] == $row["sid"]) ? " selected='selected'" : "").">{$row['sid']}</option>";
}
$dropdown .= "\r\n</select>";
3
  • there seems to be a missing bracket in your code that closes the one after selected not sure where it goes
    – Kayoti
    Sep 22, 2013 at 4:08
  • thank you though turns out the proper way of doing it is this<?php echo "<select name='codes'>"; while($row = mysql_fetch_array($result2)) { if($_POST['codes']==$row['sid']) { echo "<option selected>".$row['sid']."</option>"; } else { echo "<option>".$row['sid']."</option>"; } } echo "</select>"; ?>
    – Kayoti
    Sep 22, 2013 at 4:11
  • yes - there is a missing bracket in my soltion, but it does work. It uses an inline if statement, to remove the need for duplication of code. Sep 22, 2013 at 4:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.