PHP MySQL Query Use GROUP BY
From w3cyberlearnings
Contents |
PHP MySQL Aggregate Function GROUP BY Clause
The GROUP BY Clause is used to group the return data for the aggregate function.
Syntax
This group user by user grade.
SELECT COUNT(em.id) as total, em.grade FROM employee em GROUP BY em.grade;
Example 1
<?php define('HOST', 'localhost'); define('USER', 'root'); define('PASS', 'yeething'); define('DBNAME', 'woowood'); $connection = mysql_connect(HOST, USER, PASS) or die("can not connect to the server!<br/>"); $rdb = mysql_select_db(DBNAME) or die("The " . DBNAME . "database could not be selected"); $sel_query = "SELECT COUNT(em.id) as total, em.grade FROM employee em GROUP BY em.grade"; $result = mysql_query($sel_query, $connection) or die(mysql_error($connection)); echo '<table border="1">'; echo '<tr><th>COUNT PEOPLE</th> <th>Grade</th> </tr>'; while ($row = mysql_fetch_assoc($result)) { echo '<tr>'; foreach ($row as $value) { echo '<td>' . $value . '</td>'; } echo "</tr>"; } echo '</table>'; mysql_close($connection); ?>
Output
Related Links
- MySQL Aggregate Count
- MySQL Aggregate SUM
- MySQL Aggregate MAX
- MySQL Aggregate MIN
- MySQL Aggregate AVG
- MySQL Query Uses GROUP BY
- MySQL Query Uses Having