What are the best practices for fetching and displaying database records in PHP to avoid repeating the same data multiple times?

When fetching and displaying database records in PHP, one common issue is repeating the same data multiple times, leading to unnecessary duplication in the output. To avoid this, you can use an associative array to store unique records based on a key value, such as an ID, and then iterate through this array to display the data without duplication.

// Fetching database records
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Creating an associative array to store unique records
$records = array();
while ($row = mysqli_fetch_assoc($result)) {
    $records[$row['id']] = $row;
}

// Displaying records without duplication
foreach ($records as $record) {
    echo "ID: " . $record['id'] . "<br>";
    echo "Name: " . $record['name'] . "<br>";
    echo "Description: " . $record['description'] . "<br>";
    // Add any other fields you want to display
    echo "<br>";
}