简体   繁体   中英

Get selected dropdown option from database using PHP

I have a dropdown section menu that I need to set the selected value based on the database values.

I have a table with the following structure: id, pid, disporder, title, url

I am then using this code for the dropdown:

echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
    echo "<option value=\"".$parent['id']."\">".$parent['title']."</option>";
}
echo "</select>";

How would I go by getting the selected value based on what's in the database?

I have multiple entries in the table, so using an array with values (similar to this), isn't what I want to use:

$options = array('1', '2', '3');
foreach($options as $option)
{
    if($option = $parent['id'])
    {
        echo "selected";
    }
    else
    {
        echo "";
}

Thanks.

You haven't really given enough info to really say what the exact solution would be. If you're creating a select tag in PHP though, the typical pattern for building the markup is:

<?php

$options = get_me_some_options();
$select_markup = '<select name="my-select" id="my-select>';

foreach ($options as $key => $val) {
    $selected = '';
    if (is_this_selected($val)) {
        $selected = 'selected';
    }
    $select_markup .= "<option $selected val=\"" 
        . $val['id'] . "\">" . $val['name'] . '</option>';
}

echo $select_markup . "</select>";

It looks like your use case is similar, but slightly more complex. Ultimately though what matters is that, inside the loop, you have some way to determine whether a given row should be 'selected' or not.

If you're trying to use this in multiselects then this might help

<?php
$optionsToSelect=array(1,2,3);
?>
<select name="parent" id="parent">
<?php
foreach($allOptions as $opt){
?>
<option value="<?php echo $opt['value'];?>" <? echo $opt['selected']==1?'selected="selected"':'';?>><?php echo $opt['optTitle'];?><option>
<?php
}
?>
</select>

If I understand correctly, you want to compare each $parent['id'] with the values of an array called $options . Try this:

$options = array('1', '2', '3');

echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
    $selected = ( in_array($parent['id'], $options) ? ' selected' : '';
    echo "<option value=\"".$parent['id']."\"$selected>".$parent['title']."</option>";
}
echo "</select>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM