0

I have a date booking form which includes two input fields a start datepicker and a end datepicker. I am trying to disable dates already booked and pulled from a MySQL database using a select query. The query result is stored in an array. Each time a user submits the form the next user should not be allowed to book the same dates already booked by previous user. The big problem is my script for some unknown reason is only disabling the last inserted date range from the database. My goal is to have all previously booked dates stored in the array disabled. I have already tried assigning the query result to an array within the foreach loop $datesBooked[] = $row2['dateRange']; but with this idea none of the dates get disabled.

 <?php
//My php script 
 $statement1 = $pdo->query("SELECT dateRange FROM bookings");
 $statement1->execute();

  $datesBooked = [];


    foreach($statement1 as $row2){
        $datesBooked =  $row2['dateRange'];
                //print_r($datesBooked);        
    }

?>

$(document).ready(function(){
//My javascript
   $('#dateStart').datepicker({
        dateFormat: "yy-mm-dd",
        minDate: new Date(),
        beforeShowDay: function(date){
            var enableDays1 =  <?php echo json_encode($datesBooked);?>;
            var formattedDate = jQuery.datepicker.formatDate("yy-mm-dd", date);
            if(enableDays1.indexOf(formattedDate)==-1){ 

            return[true,'markHoliday2'];
            }else{
                return[false];

            }
        },


 });

 $('#dateEnd').datepicker({
        dateFormat: "yy-mm-dd",
        minDate: new Date(),
        beforeShowDay: function(date){
            var enableDays1 =  <?php echo json_encode($datesBooked);?>;
            var day = date.getDay();
            var formattedDate = jQuery.datepicker.formatDate("yy-mm-dd", date);
            if(enableDays1.indexOf(formattedDate)==-1){ 

            return[true,'markHoliday2'];

            }else{

            return[false];  

            }
        },


 });

 });
  • Possible duplicate of [Jquery UI datepicker. Disable array of Dates](https://stackoverflow.com/questions/15400775/jquery-ui-datepicker-disable-array-of-dates) – Michael Apr 08 '19 at 20:53

1 Answers1

0

This is because when you use $datesBooked lower down in your code, the foreach loop has finished. So you're left with only the last value - whatever the value was the last time the loop ran, because that was the last time a value was assigned to that variable. Every time the loop runs you are overwriting the value of $datesBooked with a brand new value.

Possibly you intended to add a new item to the $datesBooked array instead of overwriting the entire variable? In that case you'd need to write

$datesBooked[] =  $row2['dateRange'];

The [] means it adds a new item within the array.

ADyson
  • 57,178
  • 14
  • 51
  • 63