Insert a date before the scheduled date

4

I have a table called deliveries, within it 2 fields fecha_preparar and fecha_entrega .

$fecha_prepararse = fecha_entrega - 4 dias

INSERT INTO entregas (fecha_entrega, fecha_preparar)
VALUES ('$fecha_entrega', '$fecha_prepararse');

How can I do so that when I insert fecha_entrega I automatically insert fecha_preparar with 4 days less than fecha_entrega (the format must be on both datetime dates).

The result should be something like this:

  

date_delivery = 2017-09-05 00:00:00

     

fecha_preparar = 2017-09-01 00:00:00

Now I have this case:

tep_db_query("update " . TABLE_ENTREGAS . " set fecha_preparacion = '" . date_sub($fecha_entrega,INTERVAL 4 DAY) . "' where entregas_id = '" . (int)$entregas_id . "'");

The update is not running, it gives me the following error Parse error: syntax error, unexpected '4' (T_LNUMBER)

    
asked by Ivan Diaz Perez 02.09.2017 в 07:01
source

1 answer

4

Option 1: with MySQL

You can use date_sub , writing the query like this:

$fecha_entrega="2017-09-05 00:00:00";



INSERT INTO entregas (fecha_entrega, fecha_preparar))
    VALUES 
    ($fecha_entrega, date_sub($fecha_entrega,INTERVAL 4 DAY));

Código: Ver Demo

CREATE TABLE  IF NOT EXISTS restar_fecha (
                id SERIAL NOT NULL PRIMARY KEY,
                preparar DATETIME NOT NULL,
                entregar DATETIME NOT NULL
    );



INSERT INTO restar_fecha (entregar, preparar)
    VALUES 
    ('2017-09-05 00:00:00',date_sub('2017-09-05 00:00:00',INTERVAL 4 DAY)),
    ('2017-09-15 21:00:00',date_sub('2017-09-15 21:00:00',INTERVAL 4 DAY))

;


SELECT * FROM restar_fecha;

Resultado :

id  preparar                  entregar
1   01.09.2017 00:00:00       05.09.2017 00:00:00
2   11.09.2017 21:00:00       15.09.2017 21:00:00

Option 2: with PHP

You can use DateTime::sub

Código: Ver Demo

<?php 

$fecha_e = new DateTime('2017-09-05 00:00:00');
$fecha_entrega=$fecha_e->format('Y-m-d H:i:s'). "\n";

$fecha_p=$fecha_e->sub(new DateInterval('P4D'));
$fecha_prepara=$fecha_p->format('Y-m-d H:i:s') ;

echo "Fecha entrega: ".$fecha_entrega. "\n";
echo "Fecha prepara: ".$fecha_prepara. "\n";

/* SQL Se recomienda mejor usar consultas preparadas*/

    $sql = "INSERT INTO tabla (entrega, prepara) 
            VALUES ($fecha_entrega, $fecha_prepara);";

?>

Resultado:

Fecha entrega: 2017-09-05 00:00:00

Fecha prepara: 2017-09-01 00:00:00

We can also have a PHP function that allows more flexibility in the use of the code, in case we need to execute the operation in multiple parts of an application:

/**
 * Sustraer intervalo a una fecha dada.
 *
 *
 * @param  datetime $fecha_inicial : fecha dada.
 * @param  string   $intervalo     : Intervalo de días a sustraer.
 * @param  string   $formato       : Formato de salida de la fecha/hora.
 * @return array    $fechas        : Fechas resultantes.
 */

function sub_date ($fecha_inicial, $intervalo, $formato)
{
    $fecha_i = new DateTime($fecha_inicial);
    $fecha_inicial=$fecha_i->format($formato);

    $fecha_s=$fecha_i->sub(new DateInterval($intervalo));
    $fecha_sub=$fecha_s->format($formato) ;
    $fechas=array("inicial"=>$fecha_inicial, "sub"=>$fecha_sub);
    return $fechas;
}

The function would create an array similar to this:

Array
(
    [inicial] => 2017-09-05 00:00:00
    [sub] => 2017-09-01 00:00:00
)

Here is a test code for the function. We can pass in parameter not only the date, but also the interval that we want to subtract, and in what format we want the results:

/*Probando la función*/

$arrFechas=sub_date('2017-09-05 00:00:00','P4D','Y-m-d H:i:s');
print_r($arrFechas);
echo "Entrega: ".$arrFechas["inicial"]."\n";
echo "Prepara: ".$arrFechas["sub"]."\n";

--- Resultado

Entrega: 2017-09-05 00:00:00
Prepara: 2017-09-01 00:00:00
  

Note: To make the code more secure, it is convenient to use prepared queries.

    
answered by 02.09.2017 / 08:04
source