How can PHP be used to calculate and display available time slots for booking vehicles based on the existing booking data stored in a MySQL database?
To calculate and display available time slots for booking vehicles based on existing booking data stored in a MySQL database, we can query the database to retrieve booked time slots, then generate a list of available time slots based on a predefined time interval. This can be achieved by comparing booked time slots with the available time slots within the specified time range.
<?php
// Connect to MySQL 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 booked time slots from database
$sql = "SELECT booking_start, booking_end FROM bookings";
$result = $conn->query($sql);
$booked_slots = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$booked_slots[] = array($row['booking_start'], $row['booking_end']);
}
}
// Define time interval and generate available time slots
$start_time = strtotime('09:00'); // Start time
$end_time = strtotime('18:00'); // End time
$interval = 1800; // Time interval in seconds (30 minutes)
$available_slots = array();
for ($i = $start_time; $i < $end_time; $i += $interval) {
$slot_start = date('H:i', $i);
$slot_end = date('H:i', $i + $interval);
$is_available = true;
foreach ($booked_slots as $slot) {
if (($slot_start >= $slot[0] && $slot_start < $slot[1]) || ($slot_end > $slot[0] && $slot_end <= $slot[1])) {
$is_available = false;
break;
}
}
if ($is_available) {
$available_slots[] = array($slot_start, $slot_end);
}
}
// Display available time slots
foreach ($available_slots as $slot) {
echo "Available slot: " . $slot[0] . " - " . $slot[1] . "<br>";
}
$conn->close();
?>
Keywords
Related Questions
- How can PHP developers effectively manage and monitor email functionality to prevent abuse and ensure compliance with hosting provider policies?
- What are the best practices for handling image encoding in PHP to ensure efficient and secure processing?
- How can the PHP code be improved to handle potential errors more effectively, such as when selecting a database or executing a query?