MySQLi HAVING clause is often used with the GROUP BY clause to filter groups based on a specified condition. If the GROUP BY clause is omitted, the HAVING clause behaves like the WHERE clause
Below the syntax of HAVING clause.
SELECT expressions1,expressions2,...expressionsn ,aggregate_function(expression) FROM table_name [WHERE Clause]
GROUP BY expressions1,expressions2,...expressionsn HAVINGcondition
<?php
$conn = mysqli_connect('localhost:3306', 'user_name', 'password', 'db_nexladder');
if(! $conn) {
die('Could not connect: ' . mysqli_error());
}
$sql = "SELECT `first_name`, COUNT(*) AS total FROM `tbl_customers` GROUP BY `first_name` HAVING SUM(total) > 5";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_object($result)) {
echo "Name: " . $row->first_name. "<br />";
echo "Total: " . $row->total;
}
} else {
echo "0 rows";
}
mysqli_close($conn);
?>