使用php和mysql

时间:2016-09-27 10:22:45

标签: php mysql

我有DB,有多个表,如Regions / Countries / States / Etc。我想根据所选的其他列表制作下拉列表。

我尝试过很多东西,但似乎没什么用。

这是我的最新版本:

Core.php:

 <html>
<body>

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function abc(){
            var val = document.getElementById('Region_ID').value;
            $.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
            $("#Country_ID").html(data);

        });
 }
</script>


<form action="/NewService.php" id="ServiceForm" method="post">
  Name:<input type="text" name="Service_Name"></br>
  Region: <select name="Region_ID" onchange="abc()" form="ServiceForm">
 <?php

include('config.php');

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions"); 
    $stmt->execute();

    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 

    foreach($stmt as $v) { 
    echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";

}
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;

?>
</select></br>


Country: <select name="Country_ID" form="ServiceForm">

</select></br>


  <input type="submit">
</form>

</body>
</html>

getSecondDropDown.php:

<?php
    $Region_ID =$_POST['Region_ID'];
    $option="";
              try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'"); 
        $stmt->execute();

        $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 

        foreach($stmt as $v) { 
        echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";

    }
            echo $option;
      ?>

Image

1 个答案:

答案 0 :(得分:0)

这是您的问题,您没有在select标记

中写入id属性
<select name="Region_ID" id="Region_ID" onchange="abc()" form="ServiceForm">
  <option></option>
</select>

尝试使用javascript:

<script type="text/javascript">
function abc(){
        var e = document.getElementById("Region_ID");
        var val = e.options[e.selectedIndex].value;
        $.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
        $("#Country_ID").html(data);

    });
 }
 </script>