HTML依赖下拉菜单

时间:2014-04-06 12:25:30

标签: php html

我的HTML页面中有两个下拉列表,它从我的数据库中获取值。

我希望第二个下拉菜单取决于第一个下拉菜单中选择的值。

我试图将第一个下拉菜单的值插入到第二个下拉菜单的MySQL查询中,但想知道如何完成它。可以请某人帮我建议任何更好的方法来实现它。

<?php
include './connection.php';
$query1 = "select * from cities";
$result1 = mysql_query($query1);

echo '<select name="city" id="city">';
echo '<option value="">Select...</option>';
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="' . $row1['name'] . '">';
echo $row1['name'];
echo '</option>';

}
echo '</select>';

$query2 = "select * from cities_areas where city="<value selected in first dropdown      list>";
$result2 = mysql_query($query2);

echo '<select name="area" id="area">';
echo '<option value="">Select...</option>';
while($row2 = mysql_fetch_assoc($result2))
{
echo '<option value="' . $row2['area'] . '">';
echo $row2['area'];
echo '</option>';

}
echo '</select>';
?>

   

1 个答案:

答案 0 :(得分:0)

您必须使用表格。

<form name='myForm'>
 <select name="city" id="city" onChange="document.forms['myForm'].submit();">
  <!--your values from DB here -->
 </select>
</form>

现在,在PHP代码中编写类似(a)的内容:

$query2 = "select * from cities_areas where city='".mysql_real_escape_string($_REQUEST['city'])."'";

(a)请注意,mysql_real_escape_string是已弃用的函数,仅在此处给出。您应该使用MySQL PDO代替。

相关问题