Skip to content
PHP Logo

What is the best way to prevent duplicate year displays when outputting a list of events with PHP and MySQL?

To prevent duplicate year displays when outputting a list of events with PHP and MySQL, you can keep track of the year that has been displayed and only display it if it is different from the previous event's year. This can be achieved by storing the last displayed year in a variable and comparing it with the current event's year before outputting it.

php
// Connect to MySQL database and fetch events
$events = mysqli_query($conn, "SELECT * FROM events ORDER BY event_date");

// Initialize variable to store last displayed year
$lastYear = null;

// Loop through events and display them
while($event = mysqli_fetch_assoc($events)) {
    $eventYear = date('Y', strtotime($event['event_date']));
    
    // Check if current event's year is different from last displayed year
    if($eventYear != $lastYear) {
        echo "<h2>$eventYear</h2>";
        $lastYear = $eventYear;
    }
    
    echo "<p>{$event['event_name']}</p>";
}