How could I avoid using a MySQL query in a While loop in PHP
You may use a join query to get all the info that you need at once. Then in your application you can sort through it and display accordingly.e.g.
SELECT Classes.class, Users.NameFROM Classes JOIN Users on Classes.Teacher = Users.ID
You could use a JOIN in your initial query.
Select c.id, c.class, c.teacher, u.name from class c join user u on u.id = c.teacher
this will return all the columns from Class, plus the matched teacher name column from User, all in one query.