Save several records at the same time from a range of dates

0

I have a form in which I request 4 data; Start date, end date, note and attachment. What I try to do is that if the start date and the end date selected are different, I keep a record for each date. Example: Start date = 1-11-18 End Date = 8-11-18 Between these 2 dates there are 8 days, it would have 8 records in the database with different dates but the note and the attachment would be the same

In my database I have the fields (id, date, note, attachment)

    
asked by gmrYaeL 09.11.2018 в 20:35
source

2 answers

0

You must generate the dates that are between your start and end date, go through them and make the insert in the bd, I leave you an example:

PHP

// tus datos de entrada
$start = '2018-11-01';
$end   = '2018-11-08';


// generas las fechas entre el periodo
$end = new DateTime($end); // éstas 2 lineas son necesarias para que DatePeriod incluya la ultima fecha
$end->modify('+ 1 day');

$period = new DatePeriod(
    new DateTime($start),
    new DateInterval('P1D'), $end);

// recorres las fechas y haces tu insert
foreach ($period as $key => $value) {
    $date = $value->format('Y-m-d');

    // genera tu sql
    $sql  = "INSERT INTO tabla ('fecha', '..') VALUES ('$date', '..')";
    //echo $sql.'<br>';

    // ejecuta el sql (insert)...

}

Ex. of the generated sql:

INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-01', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-02', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-03', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-04', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-05', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-06', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-07', '..')
INSERT INTO tabla ('fecha', '..') VALUES ('2018-11-08', '..')

The proposed code works if both dates are the same and also if they are not.

Link to the official documentation on the use of DatePeriod: link

    
answered by 09.11.2018 / 23:02
source
0

I'll assume you're working in PHP

To compare dates in PHP you can do the following

$fecha_actual = strtotime(date("d-m-Y H:i:00",time()));
$fecha_entrada = strtotime("19-11-2008 21:00:00");

if($fecha_actual > $fecha_entrada)

you can use a while or a for a cycle and each time you go through the cycle you add one day

//sumo 1 día
echo date("d-m-Y",strtotime($fecha_actual."+ 1 days")); 
//resto 1 día
echo date("d-m-Y",strtotime($fecha_actual."- 1 days"));

and within the same cycle you can send to save, so you can get what you want.

    
answered by 09.11.2018 в 21:34