How can the "distinct" keyword be used in PHP to filter out duplicate entries when querying a database?
When querying a database in PHP, the "distinct" keyword can be used to filter out duplicate entries from the result set. This keyword ensures that only unique rows are returned, eliminating any duplicates that may exist in the database table. By using "distinct" in the SQL query, you can easily retrieve a list of unique values without having to manually filter out duplicates in your PHP code.
// 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 the database with distinct keyword
$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 "Column Value: " . $row["column_name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();