1

I have a dropdown box which is populated from a mysql table.

When viewing the box, the order of the options is the same as in the table e.g. a,b,c,d

I have a variable, and would like the dropdown box to be preset to that variable.

FOr example, if the variable was C, the dropdown box would automatically have C selected. The user could then change it if they wanted to.

This is the code for the dropdown box.

           <select name ='action'>
                <?php

                    $query = "SELECT action FROM actions";

                    $result = mysql_query($query);

                    while($myrow = mysql_fetch_array($result)) {
                        $action = $myrow['action'];
                        echo "<option value='$action'>$action</option>\n";
                    }       
                ?>
            </select>

I have tried adding this line above the query....

echo "<option value='$variable'>$variable</option>\n";

...however this just adds the variable as an option to the top of the list. e.g. the list a,b,c,d and when I add the above line with the variable set to B, the dropdown displays b,a,b,c,d.

Could anyone tell me how to properly preset the displayed option? Thank you

2 Answers 2

2

Try this code:

       <select name ='action'>
            <?php
                $default = 'default_value';
                $query = "SELECT action FROM actions";

                $result = mysql_query($query);

                while($myrow = mysql_fetch_array($result)) {
                    $action = $myrow['action'];
                    echo "<option value='$action'".($action == $default ? ' selected="selected"' : '').">$action</option>\n";
                }       
            ?>
        </select>

You initially set the default value you want preset. You then check with each row iteration whether the action is the default.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Works perfectly. Appreciate the help :)
0

Create a test inside the while loop. If match then add an selected inside the option tag

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.