简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM