In a table, a column contains many duplicate values; and sometimes you only want to list the different (distinct) values.
Syntax of SQL DISTINCT function and Usage:
StudentID | StudentName | ParentsContact | Address | Country | DOB | Section |
1 |
Liam | 10101010 | 23 MG road Banglore |
INDIA | 12/06 | A |
2 | Andrew | 20202020 | 2415 Anthony market str | Germany | 01/02 | A |
3 | Joshua | 30303030 | 26547 David church road | USA | 18/04 | B |
4 | Ryan | 40404040 | 18 Krishna sq. Banglore |
INDIA | 26/12 | B |
5 | Charles | 50505050 | 878 Eli Berguvsvägen 8 | INDIA | 23/11 | C |
$sql = "SELECT DISTINCT Country FROM Student";
$result = mysql_query($sql);
....
while ($row = mysql_fetch_array($result)) {
...
}
$sql = "SELECT COUNT(DISTINCT Country) FROM Student";// counts
$result = mysql_query($sql);
....
while ($row = mysql_fetch_array($result)) {
...
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>How to use SQL SELECT DISTINCT Statement in PHP</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="text-center">
<h1>SQL SELECT DISTINCT Statement in PHP</h1>
</div>
<div class="well">
<?php
$connect = mysqli_connect("localhost", "root", "", "school_management");
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$sql = "SELECT DISTINCT Country FROM Student";
if($data = mysqli_query($connect, $sql)){
if(mysqli_num_rows($data ) > 0){
echo "<table class='table'>
<tr>
<th>Country</th>
</tr>
";
while($row = $data ->fetch_assoc()){
echo "<tr>
<td>" . $row['Country'] . "</td>";
echo "<td></td>
</tr>";
}
echo "</table>";
} else{
echo "No records found.";
}
}
?>
</div>
<br>
</div>
</body>
</html>