Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected dropdown option from database using PHP

Tags:

php

mysql

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.

like image 991
Spencer Avatar asked Dec 08 '25 23:12

Spencer


1 Answers

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.

like image 58
therealjeffg Avatar answered Dec 11 '25 13:12

therealjeffg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!