使用php按类别显示表

时间:2015-03-11 08:06:31

标签: php mysql sql database

我的数据库设计是这样的

-- Table Reason
--------------------------
| reasonid  | reasonname |
--------------------------
|    1      |  reason1   |
|    2      |  reason2   |
--------------------------
-- Table Student
----------------------------
| studentid  | studentname |
----------------------------
|    1      |     John     |
|    2      |     Jane     |
|    3      |     Hulk     |
----------------------------
-- Table form
-----------------------------------
| formid  | studentid |  reasonid |
-----------------------------------
|    1    |     1     |     1     |
|    2    |     2     |     2     |
|    3    |     3     |     1     |
-----------------------------------

我想显示数据表,如:

reason1
| 1  |  John  |
| 2  |  Hulk  |
reason2
| 1  |  Jane  |

我试过下面的代码,但结果不是groupBy原因

<?php $i =1;
      while($rowfet = mysql_fetch_array($myselect)){ ?>
            <h2><?php echo $rowfet['ReasonName']; ?></h2>
            <table>
            <thead>
                <tr class="active">
                <th>No.</th>
                <th>StudentName</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                <td align="center"><?php echo $i; ?></td>
                <td><?php echo $rowfet['STUDENTNAME']; ?></td>
                </tr>
            </tbody>
            </table>
        <?php $i++; } ?>

此代码的结果是:

reason1
|  1  |  John |
reason1
|  2  |  Hulk |
reason2
|  3  |  Jane |

1 个答案:

答案 0 :(得分:0)

你可以这样做:

外面循环:

$lastReasonId = '';

在while循环中:

if($rowfet['reasonid'] != $lastReasonId){
    // show heading
}
$lastReasonId = $rowfet['reasonid'];

但你的代码还远远不够。 $ i ++的东西没有做任何事情,你应该在那里回应$ rowfet [&#39; studentid&#39;]。 并且您正在使用已弃用的mysql代码。

相关问题