How can PHP be used to check if a new appointment overlaps with existing appointments in a database?

When checking if a new appointment overlaps with existing appointments in a database, we need to compare the start and end times of the new appointment with those of existing appointments to determine if there is any overlap. This can be done by querying the database for existing appointments that fall within the same time range as the new appointment, and then checking if any overlap exists.

// Assuming $newStartTime, $newEndTime, and $appointmentDate are provided from user input

// Query to check for overlapping appointments
$query = "SELECT * FROM appointments WHERE appointment_date = '$appointmentDate' AND ((start_time < '$newEndTime' AND end_time > '$newStartTime') OR (start_time < '$newEndTime' AND end_time > '$newStartTime'))";

$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    echo "There is an overlap with existing appointments.";
} else {
    echo "No overlap with existing appointments.";
}