What is the purpose of a GROUP BY clause in PHP and how can it be implemented effectively?
The GROUP BY clause in PHP is used to group rows that have the same values into summary rows. This is often used in conjunction with aggregate functions like COUNT, SUM, AVG, etc. to perform calculations on grouped data. To implement a GROUP BY clause effectively, you need to specify the columns you want to group by in the query and include any aggregate functions as needed.
// Example of using GROUP BY clause in PHP
$query = "SELECT column1, COUNT(column2) FROM table_name GROUP BY column1";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Column 1: " . $row['column1'] . " Count: " . $row['COUNT(column2)'] . "<br>";
}
}