How can email addresses in a MySQL database be grouped by domain in an SQL query?
To group email addresses by domain in a MySQL database using an SQL query, you can use the SUBSTRING_INDEX function to extract the domain part of the email address and then use the GROUP BY clause to group the results by domain.
<?php
// Connect to MySQL 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);
}
// SQL query to group email addresses by domain
$sql = "SELECT SUBSTRING_INDEX(email, '@', -1) AS domain, COUNT(*) AS count FROM emails GROUP BY domain";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Domain: " . $row["domain"]. " - Count: " . $row["count"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- Are there any best practices or recommendations for handling session management in PHP to avoid errors like the one mentioned in the forum thread?
- What is the benefit of using PHP to structure a website compared to manually writing HTML pages?
- What are some alternatives to SOAP that may be simpler to implement in PHP projects?