select option selected according to mysql result

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomsace
Forum Contributor
Posts: 167
Joined: Thu Jan 01, 2009 8:07 pm

select option selected according to mysql result

Post by tomsace »

Hey,
Like with an input field where you can have a result from a mysql database already inputted like this:

Code: Select all

<input type="text" value="<?php echo($line['authorwebsite']); ?>">
How can I do this with a <select> drop down menu?
I have seen you have to write selected inside the <option> part of the code but how do you do this for something like this:

Code: Select all

<select name="category" class="input" style="width: 172px;">
<option value="action">Action</option>
<option value="adventure">Adventure</option>
<option value="puzzle">Puzzle</option>
<option value="shooting">Shooting</option>
<option value="role playing">Role Playing</option>
<option value="sports">Sports</option>
<option value="retro">Retro</option>
<option value="fighting">Fighting</option>
<option value="racing">Racing</option>
</select>
If the mysql result was stored as 'retro' how would I get the script to select 'retro'?
MasterBeta
Forum Commoner
Posts: 38
Joined: Thu Apr 02, 2009 4:35 am
Location: Lincoln, NE

Re: select option selected according to mysql result

Post by MasterBeta »

Code: Select all

<select name="category" class="input" style="width: 172px;">
<option value="action" <?php if($line['authorwebsite'] == "action") print "selected"; ?> >Action</option>
<option value="adventure" <?php if($line['authorwebsite'] == "adventure") print "selected"; ?> >Adventure</option>
<option value="puzzle" <?php if($line['authorwebsite'] == "puzzle") print "selected"; ?> >Puzzle</option>
<option value="shooting" <?php if($line['authorwebsite'] == "shooting") print "selected"; ?> >Shooting</option>
<option value="role playing" <?php if($line['authorwebsite'] == "role playing") print "selected"; ?> >Role Playing</option>
<option value="sports" <?php if($line['authorwebsite'] == "sports") print "selected"; ?> >Sports</option>
<option value="retro" <?php if($line['authorwebsite'] == "retro") print "selected"; ?> >Retro</option>
<option value="fighting" <?php if($line['authorwebsite'] == "fighting") print "selected"; ?> >Fighting</option>
<option value="racing" <?php if($line['authorwebsite'] == "racing") print "selected"; ?> >Racing</option>
</select>
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: select option selected according to mysql result

Post by McInfo »

See lines 27-39 of the code in this post.

Edit: This post was recovered from search engine cache.
Post Reply