What is the best way to count, sort, and display unique values from a database in PHP?

When working with a database in PHP, you may need to count, sort, and display unique values from a specific column. One way to achieve this is by using SQL queries to retrieve the unique values, count their occurrences, and then sort them as needed. By fetching the data from the database and manipulating it in PHP, you can easily achieve the desired outcome.

// Connect to the 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 to get unique values and their counts
$sql = "SELECT column_name, COUNT(*) AS count FROM table_name GROUP BY column_name ORDER BY count DESC";
$result = $conn->query($sql);

// Display the results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Value: " . $row["column_name"]. " - Count: " . $row["count"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();