Daniel Will Daniel Will - 1 year ago 75
PHP Question

check if more than 3 students belong to the same class from an array

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


} 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.

one way i thought i could be done is by placing all classes of each student in the exam in an array and then using
array_count_values
to see if there's any value that is bigger than 3, if that is possible i am not sure how it can be achieved.

Answer Source

Since your table name is students it's assumed there is one record per student. If you modify your query slightly you should be able to achieve the result without needing to count your records afterwards:

SELECT 
    class
FROM 
    students 
WHERE 
    students.id IN (" . $values . ")
GROUP BY
    class
HAVING
    COUNT(*) >= 3
;

If the query returns nothing you know there are less than 3 students in the same class. Otherwise, you will have the class(es) with 3 or more students.

However, if you want to achieve this with PHP then you will need to keep track of each class and count the student records. Here is an example:

if ( ! empty($studs)) {
    // Store the counts per class
    $class_count = array();

    foreach ($studs as $student) {

        // Add to your counter for this class
        if ( ! isset($class_count[$student['class']])) {
            $class_count[$student['class']] = 0;
        }
        $class_count[$student['class']]++;

        // Do something if you have 3 students in the same class
        if ($class_count[$student['class']] >= 3) {

            // take action

        }
    }
}

Also, as a PSA please take a look at the PHP SQL Injection page (http://php.net/manual/en/security.database.sql-injection.php) to ensure your application is protected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download