MySQLi GROUP BY statement is used with aggregate functions such as COUNT, MAX, MIN, SUM etc to group the result-set by one or more columns..
Below the syntax of GROUP BY command.
SELECT expressions1,expressions2,...expressionsn ,aggregate_function(expression) FROM table_name [WHERE Clause]
GROUP BY expressions1,expressions2,...expressionsn
<?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`";
$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);
?>