How do I assign a database query value in such a way that the value becomes the selected value in a drop down box.
I do not entirley understand the question, do you mean that you want to have some set variables, then one of them from a database, or do you want all of the options to be from the database??
Here is how i would do it for the second scenario:
<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("testbase") or die(mysql_error());
echo "<select>";
$query=mysql_query("
SELECT username
FROM users");
while($entry=mysql_fetch_array($query))
{
echo "<option";
if($entry['username']==fred){echo " selected=selected";}
echo ">" . $entry['username'] . "</option>";
}
echo "</select>";
?>
This code makes sure the option selected is the username value fred, change the if to what you need it to be
hooray
Junior Poster in Training
62 posts since Jan 2008
Reputation Points: 11
Solved Threads: 6
Ok so are you saying that you already have the values of the options in HTML, or are the values selected from the database??
hooray
Junior Poster in Training
62 posts since Jan 2008
Reputation Points: 11
Solved Threads: 6
Ok for this example i have put the option building into the code from the database
<?php
$conn=mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("testbase") or die(mysql_error());
$result=mysql_query("
SELECT *
FROM users");
$option="";
while($row=mysql_fetch_array($result))
{
$option .= "<option";
if ($_POST['name']==$row['username']) {$option.= " selected='selected'";}
$option .= ">" . $row['username'] . "</option>";
}
?>
<form method="post">
<select>
<?php echo $option; ?>
</select><input type="text" name="name" /><input type="submit" /></form>
This creates the form, and when someone types a name in the textbox and submits the form, the name they have typed gets selected in the dropdown box.
Was this what you were looking for??
hooray
Junior Poster in Training
62 posts since Jan 2008
Reputation Points: 11
Solved Threads: 6
Im going to ask a few more questions just to make sure i understand.
Where does the query come from (eg: the drop down box, a different drop down box, a text box)
Does the query come from the same field in the database as the drop box contents??
Can you give some details on your database design , and any php you might already have towards it so i can see what you are trying to do.
hooray
Junior Poster in Training
62 posts since Jan 2008
Reputation Points: 11
Solved Threads: 6