2017-03-07 130 views
1

我正在使用此查詢來連接我的學生表和考勤表,
我的問題是,有時候,考勤表沒有任何價值。
它沒有返回任何值。左連接空值表

<?php 
if($_SERVER['REQUEST_METHOD']=="POST"){ 
    include('include/connection.php'); 
    showData(); 
} 

function showData(){ 
    global $connect; 
    $teacher_id = $_POST['teacher_id']; 
    $subject_id = $_POST['subject_id']; 
    $date = $_POST['date']; 
    $query =" 
SELECT s.student_name 
    , s.student_number 
    , s.student_section 
    , s.subject_id 
    , s.fingerprint_id 
    , s.teacher_id 
    , a.status 
    FROM tbl_student s 
    LEFT 
    JOIN tbl_attendance a 
    on s.subject_id=a.subject_id 
WHERE s.subject_id = '$subject_id' 
    and a.date='$date' 
    and s.teacher_id = '$teacher_id';"; 
    $result =mysqli_query($connect,$query); 
    $number_of_rows = mysqli_num_rows($result); 
    $temp_array=array(); 

    if($number_of_rows>0){ 
     while($row=mysqli_fetch_assoc($result)){ 
      $temp_array[]=$row;  
     } 
    } 
    header('Content-Type: application/json'); 
    echo json_encode(array("student"=>$temp_array)); 
    mysqli_close($connect); 
} 


?> 

我想才達到的,即使考勤表有沒有價值,
我仍然可以看到學生的領域。
它甚至可能與SQL查詢?謝謝

+0

不包括無關的標籤,並查看有關準備和綁定查詢 – Strawberry

回答

2

你必須從where移動臺attendance領域的on條件:

$query ="SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status 
    FROM tbl_student student 
    LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date' 
    WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id';"; 

因爲語句將首先被執行的連接,然後在那裏,如果你在訪問表tbl_attendance其中ANS所有列是空的,它們將被過濾掉。

提示:瞭解準備好的發言提供SQL注入

+0

謝謝。這解決了我的應用程序的最後一個問題。非常感謝! –

+1

@CharlesGalvez不客氣 – Jens

2
SELECT student.student_name,student.student_number,student.student_section,student.subject_id,student.fingerprint_id,student.teacher_id,attendance.status 
     FROM tbl_student student 
     LEFT JOIN tbl_attendance attendance on student.subject_id=attendance.subject_id and attendance.date='$date' 
     WHERE student.subject_id='$subject_id' and student.teacher_id='$teacher_id'; 

試試上面的代碼。希望這會有所幫助。 正如您在WHERE子句中使用attendance.date='$date'條件在學生表上做出的條件,它排除了不滿足此條件的記錄。 所以,而不是我通過ON條款LEFT JOIN條款通過該條件。 這將實現您的目標。

+0

我不知道位置是非常重要的。 謝謝。問題解決了。 :D –