Click to See Complete Forum and Search --> : Select Option from database


slugmaster100
09-22-2008, 05:33 AM
hi,
i have made a select/option dropdown menu as part of a 'add user' form. One of my sections is a select as follows:

<select name="addaccount" id="addaccount">
<option value ="c">Customer</option>
<option value ="a">Administrator</option>
</select>

and when i submit my form, it adds it to the database as required & selected... so the value 'a' or 'c' goes into the database.

My problem arises when you go back to amend the user details. I can retreive all the values from the database fine (and i can echo them to confirm they are retrieved properly), but i don't know and cannot work out how to make a the same drop down box as above, but with the value from the database as the 'selected' option.

eg. say the value in the database was 'a', how can i make the same dropdown box appear, but with Administrator selected and not Customer?

Obviously i would end up expanding this for a longer options list, so radio buttons aren't a good idea for me.

thanks in advance.

Rich.

wasted
09-22-2008, 07:05 AM
This is one of the common problems of noobs. Well, let's see how can u do this.

First of all, you'll have to define those select list some where.
<?php
$arAccounts = array();
$arAccounts['a'] = 'Administrator';
$arAccounts['c'] = 'Customer'; // like wise

// store account id from db here
$dbAccountId = $row['db_account_field_name'];

?>
<select name="addaccount" id="addaccount">
<?php
foreach($arAccounts as $key => $account){
?>
<option value="<?php echo $key?>" <?php echo $dbAccountId==$key ? 'selected' : null?>><?php echo $account?></option>
<?php
}

?>
</select>

slugmaster100
09-22-2008, 10:49 AM
Tried it... works!

Thanks a lot! Saved a LOT of headaches!

Thanks

DARTHTAMPON
09-22-2008, 02:15 PM
<option value="<?php echo $key?>" <?php echo $dbAccountId==$key ? "selected=\"selected\"" : null?>><?php echo $account?></option>


Not sure how much it matters but selected="selected" is the wc3 standards. I have never had this break without using it, but I have had alot of other stuff break when future browers were released and I didnt follow the standards.