使用MySQL DB进行动态多级下拉

时间:2012-10-28 18:41:53

标签: php javascript mysql

我正在尝试创建一个多级下拉菜单,希望使用PHP,因为我之前没有javascript经验,但我也愿意学习。为了让每个人都能轻松理解我正在使用汽车作为例子。我希望用户选择福特的“品牌”示例,然后第二次下拉将填充福特所制造的“模型”,最后第三次下拉将填充福特汽车的“颜色”。我正在使用MySQL数据库,我希望动态地提取所有数据,而不是硬编码值。我能够获得第一个下拉以填充“品牌”,但当我选择“品牌”时,第二个下拉列表不会填充新结果。我是PHP和MySQL的新手,但学习速度非常快。这是我的代码:

INSERT_DROPDOWN.PHP

 <?php
$con = mysql_connect("localhost","username","XXXXXXXXXX");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("database", $con);

// Write out BRANDS.
$dquery = "SELECT brand FROM manufacture ORDER BY brand";
// Execute it, or return the error message if there's a problem.
$dresult = mysql_query($dquery) or die(mysql_error());

// Write out MODELS.
$dquery1 = "SELECT 'brand', 'model' FROM models WHERE brand='$dresult' ORDER BY model";
// Execute it, or return the error message if there's a problem.
$dresult1 = mysql_query($dquery1) or die(mysql_error());


// Write out COLORS.
$dquery2 = "SELECT color FROM color ORDER BY color";
// Execute it, or return the error message if there's a problem.
$dresult2 = mysql_query($dquery2) or die(mysql_error());

// if successful insert data into database, displays message "Successful". 
if($dresult){
echo "Successful";
echo "<BR />";
}

else {
echo "ERROR1";
}

// close connection 
mysql_close();
?>

TESTING.PHP

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <LINK href="CLL.css" rel="stylesheet" type="text/css">
        <title> 
           testing
        </title>
    </head>
    <body>

<?php 
require "insert_dropdown.php";
?>

<p>
  <?php
    //Brand
    $dropdown = "<select name='brand'>";
      while($row = mysql_fetch_assoc($dresult)) 
    {

    $dropdown .= "\r\n<option value='{$row['brand']}'>{$row['brand']}</option>";

    }

    $dropdown .= "\r\n</select>";
    echo $dropdown;

    //Model
        $dropdown1 = "<select name='brand'>";
      while($row1 = mysql_fetch_assoc($dresult1)) 
    {

    $dropdown1 .= "\r\n<option value='{$row1['model']}'>{$row['brand']}</option>";

    }

    $dropdown1 .= "\r\n</select>";
    echo $dropdown1;

    //Color
        $dropdown = "<select name='name'>";
      while($row = mysql_fetch_assoc($dresult2)) 
    {

    $dropdown .= "\r\n<option value='{$row['color']}'>{$row['color']}</option>";

    }

    $dropdown .= "\r\n</select>";
    echo $dropdown;
  ?>
</p>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

我使用AJAX

修复了代码