How can SELECT DISTINCT be used in PHP to retrieve unique values from a database?
When retrieving data from a database using SQL queries in PHP, the SELECT DISTINCT statement can be used to retrieve unique values from a specific column. This can be useful when you want to eliminate duplicate entries and only retrieve distinct values. By using SELECT DISTINCT, you can ensure that the results returned from the database query will only contain unique values.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve unique values from a specific column
$sql = "SELECT DISTINCT column_name FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Value: " . $row["column_name"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>