为每个选项创建一个Select标记,而不是为所有选项创建一个Select标记

时间:2018-07-27 11:44:51

标签: php mysql

我提取所有数据的select在单独的下拉菜单中显示了所有数据

问题:我如何在同一个下拉菜单中获得所有价目表?

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "categorys";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM all_category";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = mysqli_fetch_array( $result )) {
        echo "<select>";
        echo '<option>' . $row['category'] . '</option>';
        echo "</select>";
    }
}
?>

2 个答案:

答案 0 :(得分:0)

使您的select标签脱颖而出,并仅使用option标签:

if ($result->num_rows > 0) {
    echo "<select>";
    while($row = mysqli_fetch_array( $result )) {
        echo '<option>' . $row['category'] . '</option>';
    }
    echo "</select>";
}

此外,缩进代码会使它看起来更好。

答案 1 :(得分:0)

这是因为您要在while循环中打开和关闭新的<select>标签。这需要在循环本身之外完成:

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