How could I avoid using a MySQL query in a While loop in PHP

◇◆丶佛笑我妖孽 提交于 2019-12-23 15:22:18

问题


I have a while loop that outputs a list of classes. In the classes database the teacher name is determined by the teachers ID in the users database.

Here is my database structure.

Classes Database
-----------------------------
ID       CLASS              TEACHER
1        product design     3

User Database
-----------------------------
ID       NAME
3        John Doe

So when listing my classes I need it to convert "3" into "John Doe".

This is my current code:

<?php 
  $classdetails = mysql_query("SELECT * FROM class");
  while($class = mysql_fetch_array($classdetails)) {
    $marklist_class = $class['class'];
    $marklist_teacher = $class['teacher']; //This is a userid                                   

    //------Somewhere here i need to get the userid and look it up in the user database
    if($marklist_class=="") {

    } else {
      echo $marklist_class . ' ' . $marklist_teacher;}
    }
  }
?>

I understand just putting another mysql query there will lower performance and is not advised, so how would I look up the user database for every row without adding a query into the while loop.

Thank you.


回答1:


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.Name
FROM Classes JOIN Users on Classes.Teacher = Users.ID



回答2:


You want to use a JOIN in mysql.

SELECT * FROM class c JOIN user u ON u.ID = c.TEACHER



回答3:


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.



来源:https://stackoverflow.com/questions/10917715/how-could-i-avoid-using-a-mysql-query-in-a-while-loop-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!