How can the DISTINCT keyword be used in PHP to filter out repeated values in a query result?
When querying a database in PHP, the DISTINCT keyword can be used to filter out repeated values in the query result. By adding DISTINCT before the column name in the SELECT statement, only unique values for that column will be returned, eliminating any duplicates. This can be useful when you want to retrieve only distinct values from a database table. Example PHP code snippet:
<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Query the database with DISTINCT keyword to retrieve unique values
$query = "SELECT DISTINCT column_name FROM table_name";
$result = $connection->query($query);
// Output the unique values
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["column_name"] . "<br>";
}
} else {
echo "No results found.";
}
// Close the connection
$connection->close();
?>