Jump to content

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>';
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.