2017-08-25 64 views
-1

我遇到了麻煩,我的PHP,你可以看到,我有一個數據庫中的重複名稱(老師的第一/姓和學生的姓/名)2行。 當我使用它下面這段代碼顯示了這個網頁上Sql中的重複行標題。在PHP中打印

SubjectID: 1 
    Subject name: English 
    Teacher First Name: TeachFirst1 
    Teacher Last Name: TeachLast1 
    Class List 
    Student First Name: TeachFirst1 
    Student Last Name: TeachLast1 

我怎麼能指定,我想最後2行打印學生的第一/姓氏?不是老師。我知道爲什麼印刷老師。我只是希望它被指定

<?php  
$sql2 = 'SELECT `students`.`FirstName`, `students`.`LastName`, `subjects`.`SubjectName`, `subjects`.`SubjectNo`, `teachers`.`FirstName`, `teachers`.`LastName` 
        FROM `students` 
        INNER JOIN `timetable` ON `students`.`StudentID`=`timetable`.`StudentID` 
        INNER JOIN `subjects` ON `timetable`.`Subject`=`subjects`.`SubjectNo` 
        INNER JOIN `teachers` ON `subjects`.`TeacherID`=`teachers`.`TeacherID` 
        WHERE `timetable`.`subject`="1"'; 

      $results2 = $conn->query($sql2); 
      if($results2->num_rows > 0){ 
       while ($row=$results2->fetch_assoc()) { 
        echo "<br/>". 
        "<b>"."SubjectID: "."</b>".$row["SubjectNo"]. "<br/>". 
        "<b>"."Subject name: "."</b>".$row["SubjectName"]. "<br/>". 
        "<b>"."Teacher First Name: "."</b>".$row["FirstName"]. "<br/>". 
        "<b>"."Teacher Last Name: "."</b>".$row["LastName"]. "<br/>". 
        "<b>"."Class List"."</b>"."<br/>". 
        "<b>".'Student First Name: '."</b>".$row["FirstName"]. "<br/>". 
        "<b>".'Student Last Name: '."</b>".$row["LastName"]. "<br/>" 
        ; 
       } 
      } 
     ?> 
+0

首先做'$ arrResult = $ results2->使用fetchall的'print_r'或'var_dump'();''隨後的var_dump ($ arrResult)'。通過這樣做,你會得到一些線索來解決你的問題。 –

+0

請參閱https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-詢問 – Strawberry

回答

0

在查詢中使用別名來改變教師或學生的名字

`teachers`.`FirstName` AS t_FirstName, `teachers`.`LastName` AS t_LastName 

在同時改變

"<b>".'Student First Name: '."</b>".$row["FirstName"]. "<br/>" 

"<b>".'Student First Name: '."</b>".$row["t_FirstName"]. "<br/>",例如

1

將您的選擇更改爲以下以重命名列。

SELECT `students`.`FirstName` as studentFirstName, 
     `students`.`LastName` as studentLastName, 
     `subjects`.`SubjectName`, 
     `subjects`.`SubjectNo`, 
     `teachers`.`FirstName` as teacherFirstName, 
     `teachers`.`LastName` as teacherLastName 
.... 

而且在PHP代碼中使用指定的名稱:

"<b>"."Teacher First Name: "."</b>".$row["teacherFirstName"]. "<br/>". 
"<b>"."Teacher Last Name: "."</b>".$row["teacherLastName"]. "<br/>". 
"<b>".'Student First Name: '."</b>".$row["studentFirstName"]. "<br/>". 
"<b>".'Student Last Name: '."</b>".$row["studentLastName"]. "<br/>"