如何使用PHP和MYSQL链接下拉框?

时间:2015-10-13 07:26:24

标签: php jquery mysql database chain

这是我的db:

          [tblset]              |     [tblyear]    |    [tbl_coursetype]
ID, setname, setyear, setcours  |   ID, YearName   | course_no, course_desc   
------------------------------  | ---------------- | -----------------------
1      A        1         1     |   1   1st Year   |     1          BSIT
2      B        3         2     |   2   2nd Year   |     2          BSED
                                |   3   3rd Year   |
                                |   4   4th Year   |
                                |   5   5th Year   |
  • 这是我的代码:

        <form role="form" action="save_stud.php" method="post">
            <div class="form-group">
            <label>First Name</label>
            <input type="text" name="studfname" class="form-control" required>
            </div>
            <div class="form-group">
            <label>Last Name</label>
            <input type="text" name="studlname" class="form-control" required>
            </div>
    
    
            <div class="form-group">
            <label>Student Course</label> 
            <select name="studcourse" class="form-control">
                      <?php
    
                            // Five steps to PHP database connections:
    
                            // 1. Create a database connection
                            //      (Use your own servername, username and password if they are different.)
                            //      $connection allows us to keep refering to this connection after it is established
                            $connection = mysql_connect("localhost","root",""); 
                            if (!$connection) {
                                die("Database connection failed: " . mysql_error());
                            }
    
                            // 2. Select a database to use 
                            $db_select = mysql_select_db("studsystem",$connection);
                            if (!$db_select) {
                                die("Database selection failed: " . mysql_error());
                            }
    
                        ?>
    
                <?php
                    $result = mysql_query("Select setcours, course_desc 
                        from tblset, tbl_coursetype 
                        where tbl_coursetype.course_no=tblset.setcours 
                        group by setcours", $connection);
    
                        if (!$result) {
                        die("Database query failed: " . mysql_error());
                        }
    
    
                      // 4. Use returned data
                            while ($row = mysql_fetch_array($result)) {  
                                echo "<option value=\"{$row[0]}\">{$row[1]}</option>";  
    
                            }
    
                ?>
    
            </select> 
            </div>
    
    
            <div class="form-group">
            <label>Student Year</label> 
            <select name="studyear" class="form-control">
    
                      <?php
                            // Five steps to PHP database connections:
    
                            // 1. Create a database connection
                            //      (Use your own servername, username and password if they are different.)
                            //      $connection allows us to keep refering to this connection after it is established
                            $connection = mysql_connect("localhost","root",""); 
                            if (!$connection) {
                                die("Database connection failed: " . mysql_error());
                            }
    
                            // 2. Select a database to use 
                            $db_select = mysql_select_db("studsystem",$connection);
                            if (!$db_select) {
                                die("Database selection failed: " . mysql_error());
                            }
    
                        ?>
    
                    <?php
                    $result = mysql_query("Select setyear, YearName 
                        from tblset, tblyear
                        where tblyear.ID=tblset.setyear 
                        group by setyear", $connection);
    
                        if (!$result) {
                        die("Database query failed: " . mysql_error());
                    }
                      // 4. Use returned data
                            while ($row = mysql_fetch_array($result)) {  
                                echo "<option value=\"{$row[0]}\">{$row[1]}</option>";  
    
                            }
    
                ?>
    
    
            </select> 
            </div>
    
            <div class="form-group">
            <label>Section</label> 
            <select name="studset" class="form-control">
    
                      <?php
                            // Five steps to PHP database connections:
    
                            // 1. Create a database connection
                            //      (Use your own servername, username and password if they are different.)
                            //      $connection allows us to keep refering to this connection after it is established
                            $connection = mysql_connect("localhost","root",""); 
                            if (!$connection) {
                                die("Database connection failed: " . mysql_error());
                            }
    
                            // 2. Select a database to use 
                            $db_select = mysql_select_db("studsystem",$connection);
                            if (!$db_select) {
                                die("Database selection failed: " . mysql_error());
                            }
    
                        ?>
    
                <?php
                    $result = mysql_query("SELECT * FROM tblset t LIMIT 0,1000", $connection);
                        if (!$result) {
                        die("Database query failed: " . mysql_error());
                    }
    
                      // 4. Use returned data
                            while ($row = mysql_fetch_array($result)) {  
                                echo "<option value=\"{$row[0]}\">{$row[1]}</option>";  
    
                            }
    
                ?>
    
    
            </select> 
            </div>
    

- 这是一些截图。 Choosing course Choosing year level

现在,我感到困惑,因为BSIT只有1st year,但每当我选择BSIT时,第二个下拉列表也会显示3rd year,其中3rd year }}仅适用于BSED

简而言之,我希望每当我选择一门课程时,它会自动更改第二个下拉菜单及其相应的年级/。

我是php和mysql的新手,我不知道如何解决这个问题。我已经尝试通过互联网搜索任何代码近一周,但没有人工作,也许我不知道如何能够追踪它为什么会这样做。< / p>

有人能帮助我吗?任何帮助将不胜感激。谢谢!

4 个答案:

答案 0 :(得分:0)

了解AJAX(异步JavaScript和XML)。它将帮助您解决自动更改第二个下拉菜单及其相应的年级问题。

AJAX是一组用于客户端创建异步Web应用程序的Web开发技术。简而言之,您将能够异步地从服务器发送和检索数据,换句话说,您只能根据以前的用户输入重新加载(并因此更改内容)一个(或多个)下拉列表(无需重新加载整个页面)。据我所知,这就是你想要的。

否则你也可以在不使用AJAX的情况下实现它,但它需要整个页面重新加载。

答案 1 :(得分:0)

在加载DOM之后,您必须使用Javascript来更改页面的内容。只要选择发生变化,你就可以刷新页面,但如果我是你,我要么

  1. 将组合加载到JS对象
  2. 使用ajax异步获取它们。
  3. 你的情况相当简单,所以在我看来,后者会导致非常不必要的请求开销;如果你没有50多个年级组合的课程,我会以第一种方式接近它。这是我正在谈论的非常简单版本,使用jQuery简化:http://jsfiddle.net/eng2e9fu/

    var courses = {
        1:{years:2},
        2:{ years:3},
        };
    
    $("#course").change(function(){
        var course = $(this).val();
        var options = [];
        for(var i = 1; i <= courses[course].years; i++)
        {
            options.push($("<option/>").attr("value",i).html("Year "+i));
        }
    
        $("#year").html(options);
    });
    

答案 2 :(得分:0)

首先备份您的代码。并且,使用我的代码。我百分百肯定,它会奏效。但是,请耐心等待。并且,以非常冷静的方式使用此代码。了解每一行。

<强> dbconnect.php (在需要数据库连接的每个页面中包含此文件。为什么要编写数据库连接的每个时间代码)

<?php
$connection = mysql_connect("localhost","root",""); 
if (!$connection) {
    die("Database connection failed: " . mysql_error());
}

$db_select = mysql_select_db("studsystem",$connection);
if (!$db_select) {
    die("Database selection failed: " . mysql_error());
}
?>

您的模态页面

<?include('dbconnect.php');?>
.
//Your rest of the code
.
<form role="form" action="save_stud.php" method="post">
    <div class="form-group">
        <label>First Name</label>
        <input type="text" name="studfname" class="form-control" required>
    </div>
    <div class="form-group">
        <label>Last Name</label>
        <input type="text" name="studlname" class="form-control" required>
    </div>
    <div class="form-group">
        <label>Student Course</label> 
        <select name="studcourse" class="form-control Courses">
            <option value="">Select Courses</option>
            <?
                $QueryCourses = mysql_query("SELECT tblset.setcours, tbl_coursetype.course_desc 
                FROM tblset, tbl_coursetype WHERE tbl_coursetype.course_no=tblset.setcours", $connection);
                while ($RowCourses = mysql_fetch_array($result))
                {?>
                <option value="<?echo $RowCourses[0];?>"><?echo $RowCourses[1];?></option>
                <?}?>
        </select>
    </div>
    <div class="form-group StudentYearDiv">
        <label>Student Year</label> 
        <select name="studyear" class="form-control">
            <option value="">Select Year</option>
        </select>
    </div>
    <div class="form-group">
        <label>Section</label> 
        <select name="studset" class="form-control">
            <option value="Select Section"></option>
            <?
            $QuerySection=mysql_query("SELECT * FROM tblset LIMIT 0,1000", $connection);
            while($RowQS=mysql_fetch_array($QuerySection))
            {?>
                <option value="<?echo $RowQS[0];?>"><?echo $RowQS[1];?></option>
            <?}?>
        </select>
    </div>
    .
    .
    .
    //Your rest of the code
</form>

在页脚中添加此代码。 如果在添加后没有用,请将此代码仅保留在模态页面中。

<script>
    $('.Courses').change(function(){
        var CourseNo=$('.Courses').val();
        $.ajax({url:"Ajax-ShowStudentYear.php?CourseNo="+CourseNo,cache:false,success:function(result){
            $('.StudentYearDiv').html(result);
        }});
    });
</script>

创建一个 Ajax-ShowStudentYear.php 页面。 (请记住,如果您想更改此页面名称。那么,也要更改<script></script>标记。两者都相关)

<?
include('dbconnect.php');
extract($_GET);

$QueryYearNo=mysql_query("SELECT setyear FROM tblset WHERE setcours='$CourseNo'",$connection);
while($RowYN=mysql_fetch_array($QueryYearNo))
{
    $YearNo=$RowYN['setyear'];
}
?>

<label>Student Year</label> 
<select name="studyear" class="form-control">
    <?
    $QueryYear=mysql_query("SELECT ID, YearName FROM tblyear WHERE ID='$YearNo'",$connection);
    while($RowQY=mysql_fetch_array($QueryYear))
    {?>
        <option value="<?echo $RowQY['ID'];?>"><?echo $RowQY['YearName'];?></option>
    <?}?>
</select>

干杯!享受编码:):)

答案 3 :(得分:0)

使用您在问题中提供的数据库结构,您可以使用AJAX实现结果。

1)首先查询以获取课程......

<?php
require'connections/conn.php';

$sql = "SELECT * FROM tbl_coursetype";
$query = $conn->prepare($sql);
$query->execute();
$results = $query->fetchAll();
$totalRows = $query->rowCount();
?>

2)在<head>代码

中加入该功能
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getYears(val) {
    $.ajax({
    type: "POST",
    url: "get-year.php",
    data:'id='+val,
    success: function(data){
        $("#year-list").html(data);
    }
    });
}
</script>

3)表格

<div>
<label>Student Course</label><br/>
<select name="course" id="course-list" onChange="getYears(this.value);">
<option value="">Select Course</option>
<?php foreach($results as $row) { ?>
<option value="<?php echo $row["course_no"]; ?>"><?php echo     $row["course_desc"]; ?></option>
<?php } ?>
</select>
</div>
<div>
<label>Student Year</label><br/>
<select name="year" id="year-list">
<option value="">Select Year</option>
</select>
</div>

4)提取可用年限的sql ... get-year.php

<?php
require'connections/conn.php';

if(!empty($_POST["id"])) {
    $id = $_POST["id"];
    $sql = "SELECT * FROM tblyear WHERE ID=:id";
    $query = $conn->prepare($sql);
    $query->bindValue(':id', $id, PDO::PARAM_INT);
    $query->execute();
    $results = $query->fetchAll();
    $totalRows = $query->rowCount();
?>
    <option value="">Select Year</option>
<?php
    foreach($results as $row) {
?>
    <option value="<?php echo $row["ID"]; ?>"><?php echo $row["YearName"]; ?></option>
<?php
    }
}
?>

当然,您可以更改连接包含行以匹配您使用的内容和&amp; $conn->到您目前使用的任何内容。

快乐的编码!