Forum Moderators: coopster

Message Too Old, No Replies

trouble with php/mysql drop down list

         

bodymoves

7:17 pm on Apr 4, 2006 (gmt 0)

10+ Year Member


i have a drop down list that is populated from a table in my mysql database. im tryin to pre-select a value within the drop down and i'm having MUCH difficulty. can anyone help? here's my code...

$result = mysql_query ($query);
echo "<select name=mon_2 value=''>Contact Name</option>";
// printing the list box select command

while($nt=mysql_fetch_array($result)){
//Array or records stored in $nt

echo "<option value='$nt[name]'>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box

jatar_k

7:27 pm on Apr 4, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld bodymoves,

what value do you want to preselect? Do you have something to compare?

ChadSEO

7:30 pm on Apr 4, 2006 (gmt 0)

10+ Year Member



bodymoves,

If you want the first option in the list to be 'Contact Name', then you could do this:

$result = mysql_query ($query);
echo "<select name='mon_2'><option value='Contact Name'>Contact Name</option>";
while($nt=mysql_fetch_array($result)){
echo "<option value='$nt[name]'>$nt[name]</option>";
}
echo "</select>";

However, if 'Contact Name' is in the MySql result set, it will show up twice. To have it in there once and automatically selected, try this:

$result = mysql_query ($query);
echo "<select name='mon_2'>";
while($nt=mysql_fetch_array($result)){
echo "<option value='$nt[name]'";
if($nt[name] == 'Contact Name') { echo " selected"; }
echo ">$nt[name]</option>";
}
echo "</select>";

Chad

bodymoves

7:35 pm on Apr 4, 2006 (gmt 0)

10+ Year Member



i want to pre-select a value stored in the database (a contact's name, in this case).

jatar_k

7:40 pm on Apr 4, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



then ChadSEO's code is what you need, you just need to have the proper comparison here

if($nt[name] == 'Contact Name')

where 'Contact Name' is the value you are matching

bodymoves

7:46 pm on Apr 4, 2006 (gmt 0)

10+ Year Member



i guess i didn't explain this well, i want a value other than 'contact name' to be pre-selected.

bodymoves

7:54 pm on Apr 4, 2006 (gmt 0)

10+ Year Member



nevermind, i got it :-) THANKS SO MUCH!