Keeper
Keeper

Reputation: 37

Remember selected option within select menu

I've googled a lot and found alternative solutions but in my case things are a bit different.

<select name='database'>
    <?php foreach($databases as $row): ?>
        <option value="<?php echo $row; ?>"><?php echo $row; ?></option>
    <?php endforeach; ?>
</select>

I need to display the selected option after a POST request in between the option tags but since I already have a value for that I cannot find a way to do so. The idea is that I have one form with a couple of select menus. From the first one I select a database. The second one is for selecting a table from the already chosen database and another select menu for the columns. The problem is that I'm sending a new request for both the database and table and the chosen database cannot be remembered (it just 'resets' the select menu and starts from the first value).

Here's the whole code

Right now I need to reselect the database which I've previously chosen in order to display the columns from a table.

Upvotes: 0

Views: 1002

Answers (2)

adrian.budau
adrian.budau

Reputation: 349

Wouldn't this work?

 $dbms=$_POST['database'];
<select name='database'>
    <?php foreach($databases as $row): ?>
        <option value="<?php echo $row; ?>" 
            <?php if ($row == $dbms) echo " selected"; ?> 
        > <?php echo $row; ?></option>
    <?php endforeach; ?>
</select>

Upvotes: 1

Frederik Voordeckers
Frederik Voordeckers

Reputation: 1331

<select name='database'>
    <?php foreach($databases as $row): ?>
        <option value="<?= $row; ?>"
        <?php if ($row == $_POST['database']){echo " selected";}?>> 
            <?= $row; ?>
        </option>
    <?php endforeach; ?>
</select>

Upvotes: 3

Related Questions