Sample table
First let's take as a base the following table created in mysql:
+-------------------------+
|datetime_inicio datetime |
+-------------------------+
|datetime_fim datetime |
+-------------------------+
Fixing the current code
And now make your code work (before suggesting any improvement!). Your code has only a small error at run time. Apparently the variable $alterar_hora
was undefined (I imagine you wanted to use $inserir_data
). Making this change, the code looks like this:
<?php
//formato ano/mes/dia ou YYYY/mm/dd
$_POST['inserir_data'] = '2018/1/1';
$inserir_data = nl2br( addslashes($_POST['inserir_data']));
//formato ano/mes/dia ou YYYY/mm/dd
$_POST['inserir_turno'] = '10:30-11:40';
$inserir_turno = nl2br( addslashes($_POST['inserir_turno']));
$turno_separado = explode('-', $inserir_turno);
$hora_inicio = "$inserir_data $turno_separado[0]";
$hora_final = "$inserir_data $turno_separado[1]";
var_dump($hora_inicio);
var_dump($hora_final);
$conexao = mysqli_connect('host', 'usuario', 'senha', 'nome_banco');
mysqli_query($conexao, 'insert into teste (datatime_inicio, datetime_fim) values (\''
. $hora_inicio . '\',\'' . $hora_final .'\')');
//exibir erros na execução da instrução anterior (remover em produção).
echo mysqli_error($conexao);
What's different about your code are escapes "\ '" to allow a single quote to be inside another single quotation mark, since strings must be enclosed in quotation marks. After a few executions of the above code, the table in the database will look similar to:
+----------------------+--------------------+
|datetime_inicio |datetime_fim |
+----------------------+--------------------+
|2018-01-01 10:30:00 |2018-01-01 11:40:00 |
|2018-01-01 10:30:00 |2018-01-01 11:40:00 |
|2018-01-01 10:30:00 |2018-01-01 11:40:00 |
+----------------------+--------------------+
Improvements
Of course you could use something similar to this <input type="datetime-local" name="bdaytime">
tag to get the full datetime, and only validate it on the server. Although this does not work on all browsers (but to use plugins that allow this).