generate list of dates between 2 dates and save list in database

前端 未结 2 991
失恋的感觉
失恋的感觉 2021-01-22 09:28

I would like a bit of help with an issue I\'m currently having. I need to generate a list of dates using the first and last date in the list and then save the list of dates gen

2条回答
  •  被撕碎了的回忆
    2021-01-22 10:20

    The reason to get this error is that you call the function daterange without saving the result that it returns. So instead of calling it this way:

    daterange($booking_from, $booking_to, $step = '+1 day', $output_format = 'y-m-d');
    

    You should add the $dates variable to store the returned result of the function and to use it afterwards.

    $dates = daterange($booking_from, $booking_to, $step = '+1 day', $output_format = 'y-m-d');
    

    EDIT:

    The following code:

    
    

    returns an array of dates which is stored in the $dates param:

    Array
    (
        [0] => 2015-08-01
        [1] => 2015-08-02
        [2] => 2015-08-03
        [3] => 2015-08-04
        [4] => 2015-08-05
        [5] => 2015-08-06
        [6] => 2015-08-07
        [7] => 2015-08-08
        [8] => 2015-08-09
        [9] => 2015-08-10
    )
    

    Here is a sandbox where you can see the result.

    Please take a note here that the $output_format shold be 'Y-m-d' in order to get the date in yyyy-mm-dd format.

    You can not store an Array into a DATE field. Even if you want to store an Array, you should use the PHP's serialize function and store it in a BLOB field in the database. (See the documentation)

    So if you want to store the date range you are going to need at least two fields in the DB, e.g. date_from and date_to. In this case the INSERT statement should look like this:

    $conn->query("INSERT INTO room_nights (bookingID, apartmentID, date_from, date_to) VALUES (LAST_INSERT_ID(), '$apartment', '$dates[0]', '". $dates[count($dates) - 1] ."')");
    

    P.s. Also I saw that you are converting the $booking_from and $booking_to params multiple times from string to date - once before the daterange function definition and once in the very same function.

提交回复
热议问题