Skip to content
PHP Logo

What is the best way to retrieve the 5 most common results from a MySQL table in PHP without using multiple loops?

When retrieving the 5 most common results from a MySQL table in PHP without using multiple loops, you can achieve this by using a single SQL query with the GROUP BY and ORDER BY clauses. By grouping the results and ordering them by their frequency, you can easily fetch the top 5 most common results in a more efficient way.

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

// Query to retrieve the 5 most common results
$query = "SELECT column_name, COUNT(column_name) AS count 
          FROM table_name 
          GROUP BY column_name 
          ORDER BY count DESC 
          LIMIT 5";

$result = $mysqli->query($query);

// Fetch and display the results
while ($row = $result->fetch_assoc()) {
    echo $row['column_name'] . ": " . $row['count'] . "<br>";
}

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