Last updated on May 26th, 2016 at 11:28 am

VN:F [1.9.22_1171]
Rating: 7.3/10 (19 votes cast)

Count distinct records using MySQL PHP

This tutorial shows you how to count unique records with MySQL and display it using PHP.
This line

count(<COLUMN_NAME>) AS count_me

simply means that the count value is assigned to variable count_me and we can ECHO it using

$row['count_me']

Complete code is displayed below. Here i am using connect.php which contains the usual connecting logic to MySQL.
{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>";
$rsd = mysql_query($sql)or die("None");
while ($row = mysql_fetch_array($rsd))
{
echo $row['<TABLE_NAME>']."(".$row['count_me'].")<p>";
}
VN:F [1.9.22_1171]
Rating: 7.3/10 (19 votes cast)
3 thoughts on “Count distinct records using MySQL 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);

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
  2. Great tutorials. Really helpful information.
    Thanks for publishing.

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)

Leave a Reply

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