简体   繁体   English

通过嵌套循环遍历多个数据库表?

[英]Looping through multiple database tables with nested loop?

I have three tables in my database. 我的数据库中有三个表。 Students, modules and relations. 学生,模块和关系。 Each row of the relations table contains a student id and a module id (ie it contains the modules that a student takes). 关系表的每一行都包含一个学生ID和一个模块ID(即,它包含一个学生所采用的模块)。

I am trying to loop through the relations table and find all the modules that a particular student takes, then print out the details of each module (eg the name and module code). 我试图遍历关系表并找到特定学生所学的所有模块,然后打印出每个模块的详细信息(例如名称和模块代码)。

I am trying to do this with a nested loop however the inside loop is only running once and printing out the first module. 我正在尝试使用嵌套循环执行此操作,但是内部循环仅运行一次并打印出第一个模块。 I think this is something to do with having a second sql query inside my while loop and $m_id isnt getting updated with each iteration. 我认为这与在while循环中使用第二个sql查询和$m_id不会随每次迭代更新有关。 Here is my code so far 到目前为止,这是我的代码

<?php
        include 'connect.php';
        $sql = "SELECT * FROM relations WHERE student_id = '1'";
        $result = $conn->query($sql);
        if($result->num_rows > 0) {
            while($row = mysqli_fetch_array($result)) {
                $m_id = $row["module_id"];

                $sql = "SELECT * FROM modules WHERE module_id = $m_id";
                $result = $conn->query($sql);
                if($result->num_rows > 0) {
                    while($row = mysqli_fetch_array($result)) {
                        echo $row["module_code"];
                    }
                }
            }
        }
?>

Can anyone help me out with this? 谁能帮我这个忙吗?

You could change your SELECT query in a way that it uses a INNER JOIN to bring all modules from a specific student in one query. 您可以通过以下方式更改SELECT查询:它使用INNER JOIN将来自特定学生的所有模块带入一个查询。 Like this: 像这样:

SELECT * FROM modules
INNER JOIN relations ON relations.module_id = modules.module_id
WHERE relations.student_id = 1;

That way, it would bring all modules which have a relationship with a student of the ID of 1, assuming it's the student you desire to search through its modules. 这样,它将带与ID为1的学生有关系的所有模块,假设您是要搜索其模块的学生。 Then you would just iterate through the result array and get the values from modules that you want. 然后,您只需遍历结果数组并从所需的模块中获取值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM