php中的查询返回null或空值

时间:2017-07-04 07:32:39

标签: php mysql

我写了以下查询:

 $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并测试查询会返回预期结果,但在代码中使用查询时变量都是空的。

这些是DB的表:

会话

|Id_Session|Date|Hour|Room|Degree|

students_in_session

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

3 个答案:

答案 0 :(得分:0)

在query1中,您只是尝试将Id_session与仅需要与会话ID匹配的整个表进行比较。

只需替换此

$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')";

我觉得它对你有用。

答案 1 :(得分: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')";

检查一下。

答案 2 :(得分:0)

当您在嵌套查询中使用IN时,嵌套查询只能返回一列:

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'