如何在php中获取特定值的行数

时间:2016-10-27 06:29:33

标签: php mysql

enter image description here在我的数据库表中,有许多来自不同班级的学生。我想在表格中获得每个班级的学生人数。我怎样才能得到这个并插入表格?这是我的代码:

        <?php

        function showSearchResult()
        {
            require_once('config.php');
            connect_db(); 
            $class = '';
            $result = mysql_query("SELECT * FROM ipsc_student WHERE class=2");
            $num_rows = mysql_num_rows($result);
            $rt = "";
            $rt.="<div align='center'>
                        <h1>Report IPSC</h1>
                </div>";
            $rt.= "<table width='1000' align='center' border= '1'>";
            $rt.= "<tr><td><b>SL</b></td>
                    <td><b>Class</b></td>
                    <td><b>Total Student</b></td>
                    </tr>";
            for($i =1; $i < 13; $i++){
                $rt.="<tr>";
                $rt.="<td>$i.</td>";
                $rt.="<td>$i</td>";
                $rt.="<td>$num_rows</td>";
                $rt.="</tr>";
            } 
        echo $rt;
        }
        showSearchResult();
        ?>

2 个答案:

答案 0 :(得分:1)

您可以在学生表上进行group by课程

SELECT `class`, COUNT(`student`) AS total_student FROM `ipsc_student` GROUP BY `class`

答案 1 :(得分:0)

insert into newtablename (columnname) select count(*) from      
oldtablename group by class

newtablename - 您想要存储计数的新表 columnname - 新表中的列名 oldtablename - 想要每个班级的学生数量的旧桌子