/    Sign up×
Community /Pin to ProfileBookmark

Basing Pulldown selection off of SQL query

Hi everyone,

I am trying to automatically select a value in a pulldown menu based on the result of a SQL query.

For example if I have:

[code=php]$row[‘test’] = “mike”[/code]

and…

[code=html]<select name=”test”>
<option value=”joe”>Joe</option>
<option value=”chris”>Chris</option>
<option value=”mike”>Mike</option>
</select>[/code]

how can I have Mike selected when the page loads?

I know you can select any of these using javascript selectedIndex, but is there a way to select by the text value since this is the data stored in the Database?

Basically I need a script that if the value is set to “mike” it selects mike (the equivilent of selectedIndex[2] in JS). The selection list in question is huge (over 100 records and changes often).
Thanks!

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@jonraJun 07.2006 — The algorithm I use is:

1: Run a select to get the current value the user has chosen by grabbing it from the DB. You'll need the ID for the value and the actual display name.

2: Run a query to grab the full ist of values you wish to use to populate the select list.

3: Before you start a loop to populate the list, hard-code the HTML and use the 'selected' option. So, if you have a query with the current value that you've stored in a variable named $currentChoice, and the current ID stored in $currentID you'd say:

[code=php]<option value="<?=$currentID?>" selected><?=$currentChoice?></option>[/code]

4: This will allow the list to load with the CURRENT choice. Then, to get rid of that choice from the list, to avoid redundancy and confusion, I usually use something like this:

[code=php]
<select name="choices">
<option value="<?=$currentID?>" selected><?=$currentChoice?></option>
<?php
while($row=mysql_fetch_array($fullListResults)){
if($row['id'] != $currentID){
echo "<option value="".$row['ID']."">".$row['displayName]."</option>";
}//end if
}//end while
?>
</select>
[/code]


That's the best method I've been able to come up with.
×

Success!

Help @afail spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.30,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...