Concatenate date in PHP to insert into MySQL

3

Good morning, my question is the method of concatenating and creating a Datetime to insert into a database.

Having the variables:

$dia = '2018-04-11';
$hora = '09:36';

The desired format is: AAAA-MM-DD HH:MM:SS How do I merge and send this data to DB?

Example of what I thought:

 INSERT INTO nome_tabela (data_inicio) VALUES concat(data_inicio(Datetime?($dia,$hora))) ?? 

Can you help me compose and clarify how to create the record by that date?

    
asked by anonymous 11.04.2018 / 10:42

1 answer

7

For example:

$dia = '2018-04-11';
$hora = '09:36';

$datahora = $dia . ' ' . $hora . ':00';
//                  ^              ^--- segundos opcionais no final
//                  '--- espaço entre as partes

$sql = "INSERT INTO nome_tabela (data_inicio) VALUES '$datahora';";

For learning only, if you want CONCAT :

$dia = '2018-04-11';
$hora = '09:36';

$sql = "INSERT INTO nome_tabela (data_inicio) VALUES CONCAT('$data', ' ', '$hora', ':00')";

Note that you do not even need :00 in the end, just to illustrate. The important thing is to respect the ISO format, YYYY-MM-DD HH:MM:SS , filling from left to right.

That said, consider not working with strings this way in the application. Try to find a numerical format that fits best, to avoid having to do very complex operations with the data.

For example, dates and times with precision of seconds can be stored in integers if you use the POSIX format (up to 2038), and if you want more time, simply use an offset (eg, based on the number of seconds since the year 2010).

Alternatively, PHP has classes for date and time, but does not justify the additional cost for simple uses like yours, as it's just more code and processing to work out the same thing:

$dia = '2018-04-11';
$hora = '09:36';

$dateobject = new DateTime( $dia . ' ' . $hora );

// só faz sentido usar isso se for processar a data
// de maneira complexa antes de usar

$datahora = $dateobject->format('Y-m-d H:i:s');

$sql = "INSERT INTO nome_tabela (data_inicio) VALUES '$datahora';";
    
11.04.2018 / 11:05