1

我想用数据库中的值填充一个下拉列表。

<?php
require 'conn.php';

$filter=mysql_query("select distinct fuel_type from car");
while($row = mysql_fetch_array($filter)) {
$options ="<option>" . $row['fuel_type'] . "</option>";

$menu="<form id='filter' name='filter' method='post' action=''>
  <p><label>Filter</label></p>
    <select name='filter' id='filter'>
      " . $options . "
    </select>
</form>";

echo $menu;
}
?>

问题是我得到了两个列表,而不是一个包含值的列表。请指教

下拉列表

4

3 回答 3

2

echo $menu;应该在你的循环之外。

于 2012-04-16T02:09:55.353 回答
2

您需要$menu从循环中删除:

<?php
require 'conn.php';

$options = '';
$filter=mysql_query("select distinct fuel_type from car");
while($row = mysql_fetch_array($filter)) {
    $options .="<option>" . $row['fuel_type'] . "</option>";
}

$menu="<form id='filter' name='filter' method='post' action=''>
  <p><label>Filter</label></p>
    <select name='filter' id='filter'>
      " . $options . "
    </select>
</form>";

echo $menu;

?>
于 2012-04-16T02:11:55.960 回答
1
<?php
require 'conn.php';

$filter=mysql_query("select distinct fuel_type from car");
$menu="
<form id='filter' name='filter' method='post' action=''>
  <p><label>Filter</label></p>
    <select name='filter' id='filter'>";

// Add options to the drop down
while($row = mysql_fetch_array($filter))
{
  $menu .="<option>" . $row['fuel_type'] . "</option>";
}

// Close menu form
$menu = "</select></form>";

// Output it
echo $menu;
?>
于 2012-04-16T02:16:34.413 回答