0

I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one. So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'. How do I go about getting item2 to be selected when I load the drop down box?

1
  • i think AJAX solution will work very well ! Commented Jul 17, 2011 at 16:42

1 Answer 1

3

In your <option> element add the selected attribute for the value that is in itemschoice.

Crude example using a made up function to get the choice:

$choice = get_items_choice();
$results = mysqli_query($sql);

echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
    if ($row['choice'] === $choice) {
        echo '<option value="' . $choice . '" selected="selected" />';
    } else {
        echo '<option value="' . $choice . '" />';
    }
}
echo '</select>';

This is just an example, don't copy & paste this without adding some kind of error verification!

Sign up to request clarification or add additional context in comments.

2 Comments

I thought of that but consider this <select name="dropdown1" id="dropdown1"> <option selected="selected">Choose one</option> <option value="Item1">Item1</option> <option value="Item2">Item2</option> <option value="Item3">Item3</option> </select> If I replaced the Selected one with PHP code then Item2 would appear twice in the list.
@JosephD See my edit adding the code example. You should be able to get your list with the specific one selected without adding duplicate entries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.