douxing6532 2017-02-04 15:26
浏览 56

比较PHP中SQL的两个数组

I'm trying to read data from database, two different tables and im saving each result on an array. Next I want to compare if the results from the two queries (the arrays) are equal, for some reasons this comparison doesn't work. Any suggestion please?

 $Subjects = [];
      $var = "SELECT ID_Sub FROM Course WHERE ID_Course='$courseid'";
      $varquery= mysqli_query($conn,$var) or die(mysqli_error($conn)); 
      while($row = mysqli_fetch_array($varquery,MYSQLI_BOTH)){
        $varesiLendet[] = $rowvaresi['ID_Sub'];
      }
      $Student= [];
      $student = "SELECT ID_Sub FROM student WHERE ID_Student='$id'";
      $studentquery= mysqli_query($conn,$student) or die(mysqli_error($conn)); 
      while($rowst = mysqli_fetch_array($studentquery,MYSQLI_BOTH)){
        $Student[] = $rowst['ID_Sub'];
      }
      //checks if the two created arrays are equals
      sort( $Subjects);
      sort( $Student);
      if( $Student != $Subjects ){
        $error=true;

        echo "Not equal";
      }
  • 写回答

2条回答 默认 最新

  • duancunsu9209 2017-02-04 15:28
    关注

    It is better to do the comparison in SQL. I'm not sure exactly what you want to achieve, but this probably does what you want:

    SELECT (c.subs = s.subs) as same_flag
    FROM (SELECT GROUP_CONCAT(ID_Sub ORDER BY ID_sub) as subs
          FROM Course
          WHERE ID_Course='$courseid'
         ) c CROSS JOIN
         (SELECT GROUP_CONCAT(ID_Sub ORDER BY ID_sub) as subs
          FROM student 
          WHERE ID_Student='$id'
         ) s;
    

    Note: This directly answers the question you ask. But woe betide a student who takes a "sub" that is not part of the "course". You might want to ask another question with sample data and desired results, if the logic needs to be fixed.

    评论

报告相同问题?