Concatenate PHP date to insert into Mysql

Asked

Viewed 1,124 times

3

Good morning, my doubt consists in the method of concatenation and creation of a Datetime to insert in 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 join and send this data to the BD?

Example of what I thought:

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

They can help to compose and explain to me how to create the register with that date?

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 the CONCAT:

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

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

Note that you don’t even need the :00 at the end, just put 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 better, to avoid having to do very complex operations with the data.

For example, dates and times with seconds accuracy can be stored in integers, if using the POSIX format (up to 2038), and if you want more time, just use an offset (for example, take the number of seconds since the year 2010 as the basis).

Alternatively, PHP has classes for date and time, but it doesn’t justify the additional cost for simple uses like yours, because it’s just more code and processing to result in 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';";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.