January 31, 2021

How to create a Booking Calendar with Timeslots Php Mysql - 3

This is part 3 of How to create a Booking Calendar Php Mysql. In this tutorial we're going to add timeslots functionality to the existing calendar. This is the continuation of Part 1 and Part 2, so make sure to watch those parts first.

We will create timeslots so users can book a timeslot on any day.

The timeslots will be 15 minutes in duration, starting from 9am to 3pm.

On book.php page, first we will initialize few variables.

$duration = 15;
$cleanup = 0;
$start = "09:00";
$end = "15:00";

The $duration variable specifies the duration of a timeslot. In our case, the duration of a slot is 15 minutes.

$cleanup variable is used to add gap between two timeslots. If $cleanup is equal is 10. Then the function will add 10 minutes gap between two timeslots. For example, the first slot is 9am to 9.15am, then the next slot will start from 9.25am.

$start variable specifies start of the timeslots.

$end variable specifies end of the timeslots.

Then we'll create a function to generate timeslots using the variables above.

function timeslots($duration, $cleanup, $start, $end){
    $start = new DateTime($start);
    $end = new DateTime($end);
    $interval = new DateInterval("PT".$duration."M");
    $cleanupInterval = new DateInterval("PT".$cleanup."M");
    $slots = array();
    
    for($intStart = $start; $intStart<$end; $intStart->add($interval)->add($cleanupInterval)){
        $endPeriod = clone $intStart;
        $endPeriod->add($interval);
        if($endPeriod>$end){
            break;
        }
        
        $slots[] = $intStart->format("H:iA")." - ". $endPeriod->format("H:iA");
        
    }
    
    return $slots;
}

The above function will return an array of timeslots. It will also take 4 parameters which we initialized earlier. They are $duration, $cleanup, $start, $end.

Then finally we will call the function on our html tags.

<div class="row">
   <div class="col-md-12">
       <?php echo(isset($msg))?$msg:""; ?>
   </div>
    <?php $timeslots = timeslots($duration, $cleanup, $start, $end); 
        foreach($timeslots as $ts){
    ?>
    <div class="col-md-2">
        <div class="form-group">
           <button class="btn btn-success book" <?php echo $ts; ?>"><?php echo $ts; ?></button>
          

        </div>
    </div>
    <?php } ?>
</div>

Related Videos
How to create a Booking Calendar Php Mysql - 1
How to create a Booking Calendar Php Mysql - 2
How to create a Booking Calendar with Timeslots Php Mysql - 4
How to create a Booking Calendar with Timeslots Php Mysql - 5