0

i need to check if in an exam that contains 5 students

exist 3 students from the same class.

here is what i tried

<?
//this array contains all student id's that are in an exam
$exam = array('s1' => $s1, 's2' => $s2, 's3' => $s3, 's4' => $s4, 's5' => $s5);

$values = implode(", ", $exam);

$sql = "SELECT class FROM students WHERE students.id IN (" . $values . ")";

try{
    $db = new db();
    $db = $db->connect();
    $stmt = $db->query($sql);

    $studs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $db = null;

    if(!empty($studs)) {

        //check if 3 students from the same class are taking the exam   
        $i = 0; $s = 0;
        foreach($exam as $e )
        {
          if( !in_array( $e, $studs[$i] ) )
          {
            $exist = FALSE;
          }
          else {$s++;}
          $i++;
        }

    if ($s<=3) {
        #do sth
    }
    else {
        echo "more than 3 students";
    }

    } else {  
        echo "error";
    }
} catch(PDOException $e) {}
?>

Problem what i am not sure about is how to count that 3 students have the same class id in this exam array.

i know there is something i need to fix in my foreach just trying with no success.

mirvatJ
  • 366
  • 1
  • 3
  • 15

2 Answers2

0

You can ask your database to return all classes with 3 or more students from your id list by applying an an aggregate snd grouping your results by the class ánd using a HAVING clause:

SELECT class, COUNT(id) as num_students_in_class FROM students WHERE id IN (1,2,3,4) GROUP BY class HAVING COUNT(id) >= 3

More info: How to use group by in SQL Server query? What's the difference between HAVING and WHERE?

NSSec
  • 4,431
  • 1
  • 27
  • 29
  • No, i do not want to query it, i want to count how many students with same class id there is, as i have multiple validations i need to do – mirvatJ Oct 01 '17 at 21:45
  • plus i am not looking to query classes with 3 or more students, i am looking to find if the exam array contain more than 3 students that are in the same class – mirvatJ Oct 01 '17 at 21:55
0

If you dont want to query as suggested in https://stackoverflow.com/a/46517195/100809 you’ll need to keep an assoc array of the classes and the number of times you’ve seen it:

$seenClasses = array_count_values($studs);

foreach($seenClasses as $class => $numStudents) {
    if ($numStudents > 4)
        echo “class $class has $numStudents”;
}
NSSec
  • 4,431
  • 1
  • 27
  • 29