MySQL DISTINCT Operator in PHP

Introduction

In this article I will explain the MySQL "DISTINCT" operator in PHP. The DISTINCT operator is very helpful for eliminating duplicate records. You can use the MySQL DISTINCT operator to find the duplicate records or duplicate rows.

Syntax

SELECT DISTINCT columns FROM table_name WHERE where_conditions;

 

Example

<html>

<head>

<style>

table

{

border-style:dotted;

border-width:0px;

border-color:gray;

}

</style>

</head>

<body bgcolor="#C2DAD3">

<?php

ini_set("display_errors",0);

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

mysql_select_db("examples", $con);

$result = mysql_query("SELECT id,name,salary FROM employee ORDER BY name");

echo "<table border='1'>

<tr>

<th>id</th>

<th>name</th>

<th>salary</th>

</tr>";

while($row = mysql_fetch_array($result))

  {

  echo "<tr>";

  echo "<td>" . $row['id'] . "</td>";

  echo "<td>" . $row['name'] . "</td>";

  echo "<td>" . $row['salary'] . "</td>";

  echo "</tr>";

  }

echo "</table>";

 

mysql_close($con);

?>

</body>

</html>

In the code above you will only change the query. I will first do a query without DISTINCT:

SELECT id, name, salary FROM employee ORDER BY name;

Output

DISTINCT1.jpg

This output show all the records. I will next find the distinct records using the MySQL DISTINCT operator.

SELECT DISTINCT name FROM employee ORDER BY name;

Output

DISTINCT2.jpg

The following query is used for null values:

SELECT DISTINCT name FROM employee

Without use of the DISTINCT operator you can find duplicate records in a table as in the following:

SELECT name, salary FROM employee where salary IS not null ORDER BY name, salary

Output

DISTINCT3.jpg