1

I want $teacherIDList to include the teacherID when it loops with the same courseID for example I want it to be ('RITC01','RITC01') but at the moment it is only ('RITC01').

PHP:

function getTeacherID($subjectID) {
    require ('dbconnect.php');
    $teacherIDSQL = mysqli_query($dbc,"SELECT teacherID FROM TeacherClassRoomCourse WHERE courseID = '$subjectID'");
    $teacherIDList = [];
    while($teacherID = mysqli_fetch_array($teacherIDSQL,MYSQLI_ASSOC)) {
        array_push($teacherIDList, $teacherID['teacherID']);
        return $teacherIDList;
    }  
}
getTeacherID('COMP12');

dbconnect.php contains $dbc which connects to the database.

TeacherClassRoomCourse table:

TeacherClassRoomCourse sql table

Qirel
  • 25,449
  • 7
  • 45
  • 62
Dilly
  • 39
  • 4

2 Answers2

1

All you need to do is move the return of the array you are building outside the while loop like this

function getTeacherID($subjectID) {
    require ('dbconnect.php');
    $teacherIDSQL = mysqli_query($dbc,"SELECT teacherID FROM TeacherClassRoomCourse WHERE courseID = '$subjectID'");
    $teacherIDList = [];
    while($teacherID = mysqli_fetch_array($teacherIDSQL,MYSQLI_ASSOC)) {
        array_push($teacherIDList, $teacherID['teacherID']);

    }  
    return $teacherIDList;
}
$someting = getTeacherID('COMP12');
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1

You return inside the while loop, so it breaks after the first iteration. Move the return outside the loop so it can iterate over all the results, and not just the first.

function getTeacherID($subjectID) {
    require ('dbconnect.php');
    $teacherIDSQL = mysqli_query($dbc,"SELECT teacherID FROM TeacherClassRoomCourse WHERE courseID = '$subjectID'");
    $teacherIDList = [];
    while($teacherID = mysqli_fetch_array($teacherIDSQL,MYSQLI_ASSOC)) {
        array_push($teacherIDList, $teacherID['teacherID']);
    }  
    return $teacherIDList; // Return after while is complete
}

Notes:

  1. You're also vulnerable to SQL injection, and should use parameterized queries with placeholders instead.
  2. You're not doing anything with getTeacherID() in your code, you'll need to assign it to a variable $results = getTeacherID('COMP12');

References

Community
  • 1
  • 1
Qirel
  • 25,449
  • 7
  • 45
  • 62