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";
}
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.
Use below code
sort( $Subjects);
sort( $Student);
$result = array_diff($Subjects, $Student);
if( count($result) >0){
$error=true;
echo "Not equal";
}