How can SQL queries be optimized to prevent duplicate values in PHP output?

To prevent duplicate values in PHP output when fetching data from a SQL database, you can use the DISTINCT keyword in your SQL query to only retrieve unique values. This ensures that no duplicate values are returned in the result set.

// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Query to retrieve unique values
$query = "SELECT DISTINCT column_name FROM table_name";

// Execute the query
$result = $connection->query($query);

// Fetch and display the unique values
while ($row = $result->fetch_assoc()) {
    echo $row['column_name'] . "<br>";
}

// Close the database connection
$connection->close();