PHP Query使用两个while循环

时间:2017-03-24 03:10:34

标签: php

我的问题是表格数据中的名字与表格数据中的第二个名字相同

我想要发生的是,第一个表数据firstname应该是学生姓名,第二个表数据firstname应该是教师姓名

假设我有多个数据,所以我使用了While循环。

示例数据:

学生是John Doe和Mike Gard

教师是Myka和Jess

1st record: John Doe  Erase the Board  Done   Myka
2nd record: Mike Gard Erase the Board  Done   Myka (This should be Jess)

学校表(老师或学生) 领域:  PERSONID,  名字,  名字

任务表 领域:  PERSONID,  任务,  状态,  teacherid - >这来自人名

sql1 = select * from School S Inner Join Task T on S.personid = T.personid  // I want to get the ID of the students to get the names
sql2 = select * from School S Inner Join Task T on S.personid = T.teacherid // I want to get the ID of the teacher to get the names

<th>Student Name</th>
<th>Task</th>
<th>Teacher Name</th>
<th>Status</th >

$result1 = mysqli_query($conn, $sql1);
$result2 = mysqli_query($conn, $sql2);

while ($row1 = mysqli_fetch_array($result1)) {
    while ($row2 = mysqli_fetch_array($result2)){

        <td>".$row1['firstname']."</td>//Name of the student
        <td>".$row1['task']."</td>
        <td>".$row2['firstname']."</td>//Name of the teacher
        <td>".$row1['result']."</td>
    }   
}

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话,我认为你不需要2个单独的查询。

SELECT T.*,
S1.firstname AS studentname,
S2.firstname AS teachername
FROM Task T
LEFT JOIN School S1 ON T.personid=S1.personid
LEFT JOIN School S2 ON T.teacherid=S2.personid;

现在你可以使用一个while循环并引用$ row1 ['studentname']和$ row1 ['teachername']来代替$ row1 ['firstname']和$ row2 ['firstname']。