使用PHP分组并显示MySQL表

时间:2013-07-03 04:40:08

标签: php mysql group-by

distID   distName   regID
1        Khulna      1
2        Shatkhira   1
3        Bagerhat    1
4        Pirojpur    1
5        Barishal    2
6        Barguna     2
7        Patuakhali  2
8        Bhola       2
9        Jhalokathi  2

您好我有上表,我可以正确显示数据。我需要在输出中对regID字段进行分组。我怎样才能做到这一点?下面是我的PHP代码。

<?php
            include("db.php");


            $result=mysql_query("SELECT * from district d inner join region r on d.regID=r.regID");
        //  $result1=mysql_fetch_array(mysql_query("SELECT * FROM district"));
               // echo '<pre>';
                //print_r($result);

            while($test = mysql_fetch_array($result))
            {   //print_r($test);
                $id = $test['distID'];  
                echo "<tr align='center'>"; 
                echo"<td><font color='black'>" .$test['distName']."</font></td>";
                echo"<td><font color='black'>" .$test['regName']."</font></td>";
                echo"<td> <a href ='view.php?distID=$id'>Edit</a>";
                echo"<td> <a href ='del.php?distID=$id'><center>Delete</center></a>";

                echo "</tr>";
            }
            mysql_close($conn);
            ?>

3 个答案:

答案 0 :(得分:-1)

在查询结尾处添加GROUP BY reqID。

然而它只会返回1和2。

答案 1 :(得分:-1)

$result=mysql_query("SELECT * from district d inner join region r on d.regID=r.regID GROUP BY r.regID");

答案 2 :(得分:-1)

您只需添加GROUP BY即可,

$result=mysql_query("SELECT * from district d inner join region r on d.regID=r.regID GROUP BY `regID`");