user1475479
user1475479

Reputation: 103

PHP - Remember Selected value of Dropdownlist from mysql

I'd like to be able to remember the selected value of my dropdownlist. Whether it be from java, a Session or Cookie and have it selected accordinaly after postback. Any help would be much appreciated.

Below is my code:

            <select name="Name" onChange="showSelected(this.value)">
                <?php 
                    $qRtu = "SELECT ID, Name From tblOption";
                    $result = mysql_query($qRtu);
                    while ($data=mysql_fetch_assoc($result)){
                ?>
                <option value ="<?php echo $data['ID'] ?>" ><?php echo $data['Name'] ?></option>
                <?php } ?>
            </select>

Upvotes: 0

Views: 1145

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

You will need to put in the HTML to allow the form control to select a single selected option, something along the lines of:

<?php while ($data=mysql_fetch_assoc($result)) { ?>
    <option value ="<?php echo $data['ID'] ?>" <?php if($data['ID'] == 'some value') 
        echo( 'selected = "selected"' ); ?> >
        <?php echo $data['Name'] ?>
    </option>
<?php } ?>

The 'some_value' is something that you will need to grab from your database, or session, or cookie, or whereever you plan to grab the default value of the select box from.

Upvotes: 1

Related Questions