What is the purpose of using GROUP BY in a MySQL query in PHP?
When using GROUP BY in a MySQL query in PHP, the purpose is to group rows that have the same values in specified columns. This is useful when you want to perform aggregate functions like COUNT, SUM, AVG, etc. on those grouped rows. It helps in organizing and summarizing data based on common attributes.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query with GROUP BY
$sql = "SELECT column1, COUNT(column2) FROM table_name GROUP BY column1";
$result = $conn->query($sql);
// Loop through results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Count: " . $row["COUNT(column2)"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Related Questions
- How can the "copy" function in PHP be used effectively for file uploads without errors?
- How can the use of the move_uploaded_file() function improve the file upload process in PHP scripts?
- What is the error message "App Domains: ... should not contain protocol information" indicating in PHP Facebook App registration?