PHP MySQL Query Use Having
From w3cyberlearnings
Contents |
PHP MySQL Aggregate Function HAVING Clause
HAVING Clause is similar to the WHERE Clause, however HAVING Clause uses to filter the return data for the aggregate function. HAVING Clause comes after the GROUP BY clause.
Syntax
Filter the return data and group them by grade, return only the data that its total is larger than 3.
SELECT COUNT(em.id) as total, em.grade FROM employee em GROUP BY em.grade HAVING total > 3;
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 HAVING total > 3"; $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); ?>