Date function with two variables

0

I'm trying to concatenate a date and time so that they get the value (ISO) in MySQL so that I can insert them into the database. The line of code is this:

Example: datai = 20/04/2018 and horai = 14:27

$data = '$_POST[datai]';
$data2 = date("Y-m-d", strtotime($data)); // converter para formato definido
$hora = '$_POST[horai]'.':00'; // adicionar segundos à hora
$datahora = date('Y-m-d H:i:s', strtotime($data2.''.$hora));

However, what is received in bd is:

1970-01-01 01:00:00

Can you explain if it is possible to concatenate the date and time in this way? They are two different inputs.

The query to the database is this:

$inserirdatahora = mysqli_query ($conexao,"UPDATE minha_tabela 
SET data_de_inicio = '$datahora' WHERE (id = 10)");
    
asked by anonymous 20.04.2018 / 12:15

2 answers

0

Response that transforms two variables into one and converts from dd/mm/yyyy to yyyy-mm-dd and adds two '0' at the end of time (from 8:00 to 08:00:00).

$date1 = strtr($_POST['datai'], '/', '-');
$date2 = date('Y-m-d', strtotime($date1));
$hora = $_POST['horai'].':00';
$datahora = date('Y-m-d H:i:s', strtotime("{$date2} {$hora}"));
    
20.04.2018 / 16:30
1

Yes, it is possible, but since you set $data to '$_POST[datai]' , the variable will receive the string '$_POST[datai]' literal, not the value of $_POST['datai'] , since you used single quotation marks . As the strtotime function does not recognize this pattern, instead of giving error it will set the default date (typical of PHP not warning the developer that there is something wrong). The same happens with $_POST['horai'] .

PHP only evaluates the value of a variable inside the string when double quotes are used, such as "Você informou a data {$data}" , but in this case, why the quotes? All data coming from the HTTP request by definition are string , so it is unnecessary to "$_POST['datai']" .

The correct alternative would be:

$data = $_POST['datai'];
$hora = $_POST['horai']; // amém
$datahora = date('Y-m-d H:i:s', strtotime("{$data} {$hora}"));
    
20.04.2018 / 12:35