2017-07-04 62 views
2

我寫了下面的查詢:查詢在PHP返回null值或空值

$query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')"; 
    $res = mysqli_query($conn,$query1); 
    $query2 ="SELECT * FROM students_in_session WHERE Username='$email'"; 
    $res2 = mysqli_query($conn,$query2); 
    if (!$res) { 
    die(mysqli_error($conn)); 
}else{ 
    while ($row = mysqli_fetch_array($res)) { 
     print_r($row); 
    $course = $row['Degree']; 
    $date = $row['Date']; 
    $hour = $row['Hour']; 
    $room = $row['Room']; 
    } 
} 
if(!$res2){ 
    die(mysqli_error($conn)); 
}else{ 
    while ($row = mysqli_fetch_array($res2)) { 
     print_r($row); 
      $prof = $row['Professor']; 
     $assis = $row['Assistent']; 
    } 
} 
    return "\n\nDegree: ".$course."\n"."Date: ".$date."\n"."Hour: ".$hour."\n"."Room: ".$room."\n"."Prof: ".$prof."\n"."Assistent: ".$assis; 
} 

目前使用phpMyAdmin和測試查詢返回預期的結果,但是使用在代碼中的變量都是空的查詢。

這些數據庫的表:

會議

|Id_Session|Date|Hour|Room|Degree| 

students_in_session

|Id_Session|Code|Name|Surname|Username|Professor|Assistent| 
+0

哪個查詢返回結果?第一個或第二個或兩個 – Exprator

+0

你應該連接你的電子郵件變量,因爲PHP不能識別單引號中的變量。 ''SELECT * FROM students_in_session WHERE用戶名='$ email'「;'應該是'」SELECT * FROM students_in_session WHERE用戶名='「。 $電子郵件。 「'」;' – Edwin

+0

phpmyadmin中的所有查詢都返回結果,在我的php代碼中沒有。 – killMSN

回答

0

在QUERY1你只是嘗試,你需要主持人整個表進行比較Id_session只有會話ID。

只是

$query1 = "SELECT * FROM session WHERE Id_session IN 
(SELECT Id_Session FROM students_in_session WHERE Username = '$email')"; 

我的東西它會爲你工作,更換此

$query1 = "SELECT * FROM session WHERE Id_session IN 
(SELECT * FROM students_in_session WHERE Username = '$email')"; 

0

$query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')";

在此查詢,您必須需要選擇喜歡

$query1 = "SELECT * FROM session WHERE Id_session IN (SELECT Id_session FROM students_in_session WHERE Username = '$email')";

檢查它只有一列。

0

當您使用超過一個嵌套查詢,嵌套查詢只能返回一列:

SELECT * FROM session WHERE Id_session IN 
(SELECT Id_Session FROM students_in_session WHERE Username = '$email') 

但是嵌套查詢是不是在你的情況,最好的辦法,因爲MySQL將要執行2查詢。你最好做一個INNER JOIN:

SELECT S.* 
FROM session S 
INNER JOIN students_in_session SS ON SS.Id_Session=S.Id_Session 
WHERE SS.Username = '$email'