如何使用复选框选择从MYSQL子表中获取数据?

时间:2016-05-30 00:53:38

标签: javascript php jquery html mysql

我在使用核对表中选中的选项尝试从MYSQL中检索数据时遇到了一些麻烦。

我在MYSQL中有2个表,第1个用于degree_names - 它们作为核对表自动输出,第2个用于与每个不同程度名称相关的课程。这两个表都是关系型的,即它们是连接的,因此“courses”是“degree_names”的子表。

所以我的问题是......我该怎么做才能更改我的代码,以便我在核对清单中检查的选项(2个或更多)连接到我的“degree_names”表,然后获取与这些相关的所有课程来自“课程”表的学位?

这是我到目前为止的代码,它直接从degree_name表

输出所有度数的清单
        <?php
                $username = "root";
                $password = "";
                $hostname = "localhost";

                $dbname = "major_degrees";
                $str='';

                // Create connection
                $conn = new mysqli($hostname, $username, $password, $dbname);

                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                } 

                $sql = "SELECT degree FROM degree_names";
                $result = $conn->query($sql);

                $out = '';
                $cnt = 0;
                if ($result->num_rows > 0) {

                    // output data of each row from degree_names database as a checklist
                    while($row = $result->fetch_assoc()) {
                        $cnt++;
                        $out .= '<input id="cb_' .$cnt. '" class="checkChange" type="checkbox" name="check" value="ch" id="checky" />' .$row['degree']. '<br/>';

                    }
                    echo $out;  

                } 

        ?>
    </b>
    </br>
    <input class="btn-checkout" type="submit" value="Submit" id="submitBtn" disabled="disabled"/>
    </div>
    </div>


        </form>
        </body>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
        <script>
            $('.checkChange').change(function() {
                var count = 0;
                var len = $("[name='check']:checked").length;               

                // keep a counter for how many boxes have been checked
                $('#checkboxes input:checked').each(function() {
                    count++;
                });

                // if 2 boxes are checked off then disable the rest
                if (count == 2) {
                    $('#checkboxes input:not(:checked)').each(function() {
                        $(this).attr("disabled", true);

                    }); 

                } 
                // else keep other options enabled
                else {
                    $('#checkboxes input:not(:checked)').each(function() {
                        $(this).removeAttr('disabled');
                    });                                     
                }   

                //if exactly 2 boxes are checked off then enable the submit button, or else keep is disabled
                if ($(this).is(":checked") && count == 2) {
                        $("#submitBtn").removeAttr("disabled");
                } else {
                        $("#submitBtn").attr("disabled", "disabled");
                }

            });

        </script>

    </html>

1 个答案:

答案 0 :(得分:1)

首先清楚majorscourses表之间的关系:

您的majors表格如下:

 degree_id | TotalCredits |    degree_name
-----------+--------------+--------------------
     1     |      8       |     Computer Science
     2     |     8.5      |      Mathematics
     3     |      8       |    Music and Culture

courses表:

 id | course_id | degree_id |            course_name               | credits | pre-requisite | last-offered | status |
----+-----------+-----------+--------------------------------------+---------+---------------+--------------+--------+
 1  |   CSCA08  |     1     | Introduction to Computer Science I   |   0.5   |     CSCA48    |   Fall 2015  |        |
 2  |   CSCA48  |     1     | Introduction to Computer Science II  |   0.5   |     CSCB07    |  Winter 2015 |        |
 3  |   MATA23  |     2     |         Linear Algebra I             |   0.5   |     MATB24    |   Fall 2015  |        |

为什么每个复选框都有一个value?将这些复选框的值设置为degree_id表的majors。首先将您的查询更改为:

$sql = "SELECT degree_id, degree_name FROM majors";

然后将复选框的值设置为:

$out .= '<input id="cb_' .$cnt. '" class="checkChange" type="checkbox" name="check" value="'.$row['degree_id'].'" id="checky" />' .$row['degree_name']. '<br/>';

然后让我们有一个空表来显示数据:

<table id="course_table">
</table>

然后使用Ajax来调用显示:

$(document).on("change", ".checkChange", function(){ /* WHEN A CHECK BOX HAS BEEN TICKED */

     var counter = 0;

     /* COUNT ALL THE CHECKED CHECK BOXES */
     $(".checkChange").each(function(){
         if(this.checked){
             ++counter;
         }
     });

     if(counter == 2){ /* IF CHECKED CHECK BOXES REACHED TWO */
         /* DISABLE OTHER UNCHECKED CHECK BOXES */
         $(".checkChange").each(function(){
             if(!this.checked){
                 $(this).prop("disabled", true);
             }
         });
     } else {
         /* ENABLE ALL CHECK BOXES */
         $(".checkChange").prop("disabled", false);
     }

     $("#course_table").empty(); /* EMPTY THE TABLE */

     $('#checkboxes :checked').each(function() { /* CHECK EACH CHECKED CHECK BOXES */

         var degid = $(this).val(); /* GET THE VALUE OF THE CHECKED CHECK BOX */

         $.ajax({ /* CALL AJAX */
             type: 'POST', /* METHOD TO USE TO PASS THE DATA */
             url: 'get.php', /* FILE WHERE TO PROCESS THE DATA */
             data: { 'degid' : degid }, /* DATA TO BE PASSED */
             success: function(result){ /* GET THE RESULT FROM get.php */
                 $("#course_table").append(result); /* ADD THE COURSES RESULT TO THE HTML TABLE */
             }
         }); /* END OF AJAX */

     }); /* END OF CHECKING EACH CHECKED CHECK BOXES */

}); /* END OF IF A CHECK BOX HAS BEEN TICKED */

您可能会注意到我们将处理get.php中的值,因此我们创建此文件。让我们使用prepared statement

// INCLUDE YOUR DATABASE CONNECTION
$conn = new mysqli('localhost', 'root', '', 'major_degrees');

// CHECK CONNECTION
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

if(!empty($_POST["degid"])){

    $stmt = $conn->prepare("SELECT course_name FROM courses WHERE degree_id = ?"); /* PREPARE YOUR QUERY */
    $stmt->bind_param("i", $_POST["degid"]); /* BIND THE SUBMITTED DATA TO YOUR QUERY; i STANDS FOR INTEGER */
    $stmt->execute(); /* EXECUTE QUERY */
    $stmt->bind_result($coursename); /* BIND RESULT TO THIS VARIABLE */
    while($stmt->fetch()){ /* FETCH ALL RESULTS */
        echo '<tr>
                  <td>'.$coursename.'</td>
              </tr>';
    }
    $stmt->close(); /* CLOSE PREPARED STATEMENT */

}
/* WHAT YOU ECHO/DISPLAY HERE WILL BE RETURNED TO degree.php */