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
- How can PHP developers optimize their code by implementing loops and break statements when working with arrays?
 - What best practices should be followed when setting IDs for elements in the <body onload...> attribute in PHP-generated HTML code?
 - How can JSON data retrieved from curl requests be deserialized and structured for further processing in PHP?