Last updated on April 8th, 2022 at 02:13 pm

This tutorial shows you how to count unique records inside MySQL table and display it using PHP.
Use the below SQL query to count the column

SELECT UPDATE_TIME, count(UPDATE_TIME) AS count_me FROM TABLES GROUP BY UPDATE_TIME ORDER BY COUNT(UPDATE_TIME) DESC;

In the above example I am selecting a column named UPDATE_TIME, this simply means that the count value is assigned to variable count_me and we can display the result it using PHP, I am explaining that below.

$row['count_me']

Complete code is displayed below. Below I have provided an include statement to load connect.php that contains the usual connecting logic to MySQL.

Modify these variables
{column_name} refers to your COLUMN NAME
{table_name} refers to your TABLE NAME

include("connect.php");
$sql = "SELECT column_name, count(column_name) AS count_me FROM table_name GROUP BY column_name ORDER BY COUNT(column_name) DESC";
$rsd = mysqli_query($conn,$sql)or die("None");
while ($row = mysqli_fetch_array($rsd))
{
echo $row['column_name']."(".$row['count_me'].")<p>";
}

3 thoughts on “How to count distinct records in MySQL using PHP”
  1. This is the simplest code to select and display records from MySQL database table and display in PHP.

    $cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
    mysql_select_db($db_name,$cn) or die(mysql_error());

    $sql = “SELECT field_name FROM table_name”;
    $rs = mysql_query($sql) or die(mysql_error());

    while($row = mysql_fetch_array($rs)){

    echo $field_name = $row[“field_name”];
    echo “”;

    }
    mysql_free_result($rs);

Leave a Reply

Your email address will not be published. Required fields are marked *