在表内分组数据

时间:2014-02-11 14:41:16

标签: javascript php mysql

我有这样的代码

<table>
            <tr>
            <th> Subject </th>
            <th> Description </th>
            <th> Units </th>
            <th> Prerequisite Subject</th>
            </tr>
<?php
$dep = $_SESSION['course'];

$con = mysql_connect("localhost","root","");
        if(!$con){
        die('Could not connect to database' .mysql_error());
        }
        else{
        mysql_select_db("enrollment", $con);
        }       
        $result = mysql_query("SELECT * FROM tblsubject where department='$dep' order by year asc, semester asc ");
        if(!$result){
        die('Invalid query:' .mysql_error());
        }
        else{
        $cur_year= '';
        $cur_semester = '';
        while($row = mysql_fetch_array($result))
        {
        if($cur_year !== $row['year'] or $cur_semester !== $row['semester']){
        echo'<tr>';
        echo'<td colspan="7" align="center"><b>'.$row['year'].'</b></td>';
        echo'</tr>';
        echo'<tr>';
        echo'<td colspan="7" align="center"><b>'.$row['semester'].' Semester</b></td>';
        echo'</tr>';

        $cur_year = $row['year'];
        $cur_semester = $row['semester'];

        $sequel = "select sum(units) as sum_value from tblsubject where department='$dep' and year='$cur_year' and semester='$cur_semester' order by year asc, semester asc";
        $results = mysql_query($sequel);

        $cur_unit= '';

        while($rrr = mysql_fetch_assoc($results)){
        if($cur_unit!== $row['units']){
        echo'<tr>';
        echo'<td colspan="7" align="right"><b>Total Of : '.$rrr['sum_value'].' Units</b></td>';
        echo'</tr>'; 

        $cur_unit = $rrr['sum_value'];
        }
        } 
        }

        echo'<tr>';
        echo'<td>'.$row['sub_code'].'</td>';
        echo'<td>'.$row['sub_desc'].'</td>';
        echo'<td>'.$row['units'].'</td>';
        echo'<td>'.$row['prereq'].'</td>';
        echo'</tr>';

        }
        }

?>  
        </table>    

我有这样的输出。

| Subject | Description | Units | Prerequisite Subject|
|                   First Year                        |
|                First Semester                       |
|                 Total Units : 3 Units               |
|  IT111  | IT Major    |   3   |      none           |

我想在每个学期将总单位放在所列主题的底部。

必须是这样的。

| Subject | Description | Units | Prerequisite Subject|
|                   First Year                        |
|                First Semester                       |
|  IT111  | IT Major    |   3   |      none           |
|                 Total Units : 3 Units               |

因为如果我将下面的总单位代码用于计算单位,则在添加的每一个主题之后将输出总数。

1 个答案:

答案 0 :(得分:0)

使用mysql是折旧的,你应该考虑使用PDO或mysqli,它们都有返回行数的语句。 http://au1.php.net/manual/en/mysqli-stmt.num-rows.php代表mysqli,http://au1.php.net/manual/en/pdostatement.rowcount.php代表PDO。

如果你仍然想使用MySQL,那就是mysql_num_rows。

一旦你了解了PDO,你应该没有问题。