Jump to content

[SOLVED] dynamic form option list


tippy_102

Recommended Posts

I want to create a dynamic drop down option list in a form, but I just can't wrap my head around this.

 

Both of the below scripts work as intended, but how do I make the mySql query results work with my existing script?  Yes, I know I must replace the "$options = array" part in the top piece of code, but I need a little more guidance than that.

 

<?php
function select_menu($name, $options, $selected) { 
    $list = ''; 
    foreach ($options as $value => $text) { 
        $is_selected = $value == $selected ? ' selected="selected"' : ''; 
        $list .= "  <option value=\"$value\"$is_selected>$text</option>\n"; 
    } 
    return "<select name=\"$name\" id=\"$name\">\n$list</select>\n"; 
}

echo "<tr><td>size:</td><td>";

$options = array( 
    '0' => 'select an option', 
    '1' => 'Micro', 
    '2' => 'Small', 
    '3' => 'Regular',
    '4' => 'Large' 
); 

$menu_name = 'size'; 
// grab selected_val from db 
$selected_value = $size; 

echo select_menu($menu_name, $options, $selected_value); 

echo "</td></tr>";	

?>

 

<?php
$query = "SELECT * FROM topic_size"; 
$result = mysql_query($query) or die(mysql_error());

while($options = mysql_fetch_array($result))
{
echo $options['topID']. $options['topicName'];
echo "<br>";
}
?>

Link to comment
https://forums.phpfreaks.com/topic/43268-solved-dynamic-form-option-list/
Share on other sites

Very similar to array version

 

function selectMenu ($name, $selected) 
{
        $query = "SELECT topID, topicName FROM topic_size"; 
        $result = mysql_query($query) or die(mysql_error());

        echo "<select name='$name'><option value='0'>select an option</option>"; 
        while(list($value, $text) = mysql_fetch_row($result))
        {
        $sel = $value=$selected ? 'selected' : '';
            echo "<option value='$value' $sel> $text</option>";
        
        }
        echo '</select>';
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.