将所有值从DB调用到下拉列表

时间:2014-01-21 14:36:29

标签: php html mysql arrays select

我有一个材料表,其中所有材料都插入到desc列中。 desc值可以尽可能多。

样品:

desc
 poly canvass
 metal
 washer
 knot

这是我做的代码。

<?php 
$resource=mysql_query("Select * from material",$con);

while($result2=mysql_fetch_array($resource))
    { 

    ?>
<select>
<option value="<?php echo $result2[desc] ?>"><?php echo $result2[desc] ?></option>
</select>

</tr>
<?php };?>

但它会生成四个下拉列表,对应于我的数据库中的四个值 像:

dropdown1      dropdown2      dropdown3      dropdown4
polycanvass    metal          washer         knot

如何让desc列中的所有值显示在一个下拉列表中?

3 个答案:

答案 0 :(得分:1)

    <?php 
    $resource=mysql_query("Select * from material",$con);
    ?>
    <select>
    <?php
    while($result2=mysql_fetch_array($resource))
    {
    ?>
    <option value="<?php echo $result2[desc] ?>"><?php echo $result2[desc] ?></option>
    <?php
    }
    </select>
    ?>

select应该不在while循环中,因为对于每个值,它也会重复,并且最终会有与总记录数一样多的下拉。

答案 1 :(得分:0)

从while循环中取出select标签并将其放在外面。

我建议您使用mysqli而不是mysql

PHP MySQLi = PHP MySQL改进了!

注意: MySQLi扩展程序适用于MySQL 4.1.13或更高版本

<?php
    $con=mysqli_connect("host","username","password","dbname");
    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    $resource= mysqli_query($con,"SELECT * FROM material");

    echo "<select>";
    while($result = mysqli_fetch_array($resource)){
        echo '<option value="'.$result[desc].'">'.$result[desc].'</option>';
    }
    echo "</select>";

    mysqli_close($con);
?>

答案 2 :(得分:0)

 <?php 
    $resource=mysql_query("Select * from material",$con);
    ?>
    <select>
    <?php
    while($result2=mysql_fetch_array($resource))
    {
    echo '<option value="'.$result2[desc].'">'.$result2[desc].'</option>';
    }
?>
    </select>

选择退出循环和输出<option>

的更短方式
相关问题