0
Follow
0
View

Condition not working with PHP and mysqli

dgsdeng 注册会员
2023-01-24 23:35

Once you've assigned a student to a teacher, you should break out of the teacher loop, so you don't try to assign the student to another teacher.

When you assign a student to a teacher, you need to increment $info['assigned']. And in order to do this, your iteration variable needs to be a reference to the array element; otherwise you get a copy of the array, which won't affect future iterations.

In the code below, I've converted all the queries to prepared statements.

$conn = mysqli_connect($serverName, $user, $password, $dbName);
if(mysqli_connect_errno()){
    echo "Failed to connect to mysqli.".mysqli_connect_errno();
} else {
    $insert_assignment_stmt = $conn->prepare("INSERT INTO assignment(student_name, advisor_name, subject) values(?, ?, ?)");
    $insert_assignment_stmt->bind_param("sss", $name_student, $name_teacher, $subject);
    $update_teacher_stmt = $conn->prepare("UPDATE teachers SET assigned = assigned + 1 WHERE name = ?");
    $update_teacher_stmt->bind_param("s", $name_teacher);
    $update_student_stmt = $conn->prepare("UPDATE students SET assigned = 1 WHERE name = ?");
    $update_student_stmt->bind_param("s", $name_student);

    foreach($students_info as &$student_info){
        foreach($teachers_info as &$teacher_info){
            if($student_info['assigned'] == 0 && $student_info['ee_subject'] == $teacher_info['ee_subject_1_choice'] && $teacher_info['assigned'] < 4 ){
                $name_student = $student_info['name'];
                $name_teacher = $teacher_info['name'];
                $subject = $student_info['ee_subject'];

                $insert_assignment_stmt->execute();
                $update_teacher_stmt->execute();
                $update_student_stmt->execute();

                $teacher_info['assigned']++;

                break;
            }
        }
    }
}
mysqli_close($conn);