How can the 'group by' and 'count' functions be utilized in PHP to count the occurrence of each IP address in a MySQL table?

To count the occurrence of each IP address in a MySQL table using PHP, you can use the 'group by' and 'count' functions in a SQL query. By grouping the IP addresses together and counting the number of occurrences, you can retrieve the count for each unique IP address in the table.

<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Query to count occurrence of each IP address
$query = "SELECT ip_address, COUNT(*) as count FROM table_name GROUP BY ip_address";

// Execute the query
$result = $mysqli->query($query);

// Loop through the result and display the count for each IP address
while($row = $result->fetch_assoc()) {
    echo "IP Address: " . $row['ip_address'] . " - Count: " . $row['count'] . "<br>";
}

// Close database connection
$mysqli->close();
?>