如何避免在PHP的While循环中使用MySQL查询 [英] How could I avoid using a MySQL query in a While loop in PHP

查看:240
本文介绍了如何避免在PHP的While循环中使用MySQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个while循环,输出一个类列表.在班级数据库中,教师姓名由用户数据库中的教师ID决定.

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.

这是我的数据库结构.

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

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

因此,在列出我的课程时,我需要它将"3"转换为"John Doe".

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

这是我当前的代码:

<?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;}
    }
  }
?>

我了解仅在此处放置另一个mysql查询会降低性能,因此不建议这样做,因此我如何在不将查询添加到while循环中的情况下查找每一行的用户数据库.

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.

谢谢.

推荐答案

您可以使用联接查询来一次获取所需的所有信息.然后,您可以在应用程序中对其进行排序并进行相应显示. 例如

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

这篇关于如何避免在PHP的While循环中使用MySQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆