如何在从MySQL数据库填充的PHP中创建动态下拉列表

时间:2013-07-17 05:40:26

标签: php html mysql dynamic drop-down-menu

我正在尝试使用PHP和mysql数据库创建动态下拉列表。我写了下面的代码,它给了我输出,但问题是它显示每个项目的不同下拉菜单,我想在一个下拉列表中的所有项目。请检查并指导我。

        $select_query=          "Select name from category";
        $select_query_run =     mysql_query($select_query);
        while   ($select_query_array=   mysql_fetch_array($select_query_run) )
        {
            foreach ($select_query_array as $select_query_display)
            {
                echo "  
                    <select>
                        <option value='' >$select_query_display</option>                        
                    </select>
                ";


                }

            }

谢谢

5 个答案:

答案 0 :(得分:4)

摆脱内部的foreach循环...它对你没有任何作用,并在while循环之外移动开始和结束选择标记。

$select_query=          "Select name from category";
$select_query_run =     mysql_query($select_query);
echo "<select name='category'>";
while ($select_query_array=   mysql_fetch_array($select_query_run) )
{
   echo "<option value='' >".htmlspecialchars($select_query_array["name"])."</option>";
}
echo "</select>";

答案 1 :(得分:1)

看看这段代码。

$select_query=          "Select name from category";
$select_query_run =     mysql_query($select_query);

echo "<select>";
while   ($select_query_array=   mysql_fetch_array($select_query_run) )
{
        echo "<option value='' >".$select_query_array['name']."</option>";                        
}
echo "</select>";

答案 2 :(得分:0)

$select_query= "Select name from category";
$select_query_run =     mysql_query($select_query);
$selectTag = "<select>";
while   ($select_query_array=   mysql_fetch_array($select_query_run) ){
    foreach ($select_query_array as $select_query_display){
        $selectTag .="<option value='' >$select_query_display</option>";
    }
}
$selectTag .= "</select>";

   echo $selectTag;

答案 3 :(得分:0)

<?php

$res = mysqli_query($conn, "SELECT DISTINCT coloumn_name FROM table_name;" );
while($row = mysqli_fetch_array($res))    
{
    echo "<option value='" . $row['selected_coloumn']. "'>" . $row['selected_coloumn'] . "</option>";
}
?>

在此示例中,请选择'coloumn_name''table_name'

答案 4 :(得分:0)

你可以尝试一下

    $select_query=          "Select name from category";
    $select_query_run =     mysql_query($select_query);
    $select_query_array=   mysql_fetch_array($select_query_run)
    $select = "<select>";
    foreach ($select_query_array as $val)
    {
        $select .= "<option value='".$val['name']."' >".$val['name']."</option>"; 


    }

    $select = "</select>";

    echo $select;

希望它会起作用