需要帮助迭代PHP中的mysql结果集

时间:2013-04-21 12:23:34

标签: php mysql

我有两张桌子:

Institute:
-----------
id       name         city
-----    -------      -------
1        Name 1       London    
2        Name 2       Leeds
3        Name 3       Edinburgh

Course:
--------
id       i_id     name                      stream
-----    -----    --------------------      -------
1        1        Computer Engineering      Engineering 
2        1        Chemical Engineering      Engineering
3        2        Electronics Engineering   Engineering 
4        3        Mechanical Engineering    Engineering

我需要在结果集中提供以下信息:

  1. 提供工程课程的学院(名称1,名称2,名称3)。
  2. 学院提供的所有课程。
  3. 现在,这是我的查询来实现这个结果集:

    SELECT institute.id, institute.name AS i_name, institute.city, course.name AS c_name
    FROM institute, course
    WHERE institute.id = course.i_id
    AND course.stream = 'Engineering'
    ORDER BY institute.id
    

    此查询返回4条记录:

    id      i_name      city           c_name
    ---     -------     ---------      ----------------
    1       Name 1      London         Computer Engineering
    1       Name 1      London         Chemical Engineering
    2       Name 2      Leeds          Electronics Engineering
    3       Name 3      Edinburgh      Mechanical Engineering
    

    如何迭代此结果集以便我在网页上方的数据列表下方:

     Found 3 Institutes
     ----------------------
     1) Name 1, London
        Courses Offered:-
        => Computer Engineering
        => Chemical Engineering
    
     2) Name 2, Leeds
        Courses Offered:-
        => Electronics Engineering
    
     3) Name 3, Edinburgh
        Courses Offered:-
        => Mechanical Engineering
    

    [ ADDED

    我的网页上有分页设置。现在假设我想在每页显示2条记录,我将使用LIMIT 0,2运行上述查询。现在显然我的查询中的前两条记录给了我同一个机构,所以在这种情况下我也需要第三个机构。

    我可以制作这样的动态查询吗?

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

$currentInstitute = null;
$i = 1;
while($row = mysql_fetch_object($query)) {
  if($row->i_name != $currentInstitute)
    echo $i++.") $row->i_name, $row->city\n   Courses offered:-\n";
  $currentInstitute = $row->i_name;
  echo "    => $row->c_name\n"; 
}