首页 > 解决方案 > SQL,在计算两次之间的差异时插入表

问题描述

我目前正在使用 fullcalendar 制作一个简单的日历。我的数据库有三个日期时间:

start 
end
total

我想要的是程序在插入日期时计算开始和结束之间的差异并将其添加到总数中。这是我的插入 SQL 代码:

我在 MySQL 中使用 InnoDB。

session_start();

include_once './conexao.php';

$dados = filter_input_array(INPUT_POST, FILTER_DEFAULT);

//Converter a data e hora do formato brasileiro para o formato do Banco de Dados
$data_start = str_replace('/', '-', $dados['start']);
$data_start_conv = date("Y-m-d H:i:s", strtotime($data_start));

$data_end = str_replace('/', '-', $dados['end']);
$data_end_conv = date("Y-m-d H:i:s", strtotime($data_end));

$query_event = "INSERT INTO events (title, name, color, start, end, total) "
        . "VALUES (:title, :name, :color, :start, :end) "
        . "SELECT DATEDIFF(':start', ':end') AS total";

$insert_event = $conn->prepare($query_event);
$insert_event->bindParam(':title', $dados['title']);
$insert_event->bindParam(':name', $dados['name']);
$insert_event->bindParam(':color', $dados['color']);
$insert_event->bindParam(':start', $data_start_conv);
$insert_event->bindParam(':end', $data_end_conv);

if ($insert_event->execute()) {
    $retorna = ['sit' => true, 'msg' => '<div class="alert alert-success" role="alert">Evento inserido com sucesso!</div>'];
    $_SESSION['msg'] = '<div class="alert alert-success" role="alert">Evento inserido com sucesso!</div>';
} else {
    $retorna = ['sit' => false, 'msg' => '<div class="alert alert-danger" role="alert">Erro: Evento não foi inserido com sucesso!</div>'];
}


header('Content-Type: application/json');
echo json_encode($retorna);```


标签: phpmysqlsqlpdo

解决方案


我可以从外观中看出您一定遇到了 SQL 语法错误 - 您不能在同一个查询中使用INSERT...VALUESINSERT...SELECT语法 - 您必须使用其中一个。但是您不需要SELECT这里,您可以将 DATEDIFF 函数作为值之一。您也不需要在传递给 DATEDIFF 的参数周围加上引号。

您也不能在 PDO 中两次使用相同的参数名称。

我认为这应该会更好(尽管显然我无法对其进行测试):

$query_event = "INSERT INTO events (title, name, color, start, end, total) "
        . "VALUES (:title, :name, :color, :start, :end, DATEDIFF(:start2, :end2))";

$insert_event = $conn->prepare($query_event);
$insert_event->bindParam(':title', $dados['title']);
$insert_event->bindParam(':name', $dados['name']);
$insert_event->bindParam(':color', $dados['color']);
$insert_event->bindParam(':start', $data_start_conv);
$insert_event->bindParam(':end', $data_end_conv);
$insert_event->bindParam(':start2', $data_start_conv);
$insert_event->bindParam(':end2', $data_end_conv);

PS 如果你在运行代码的时候还有其他问题,你需要具体解释一下,因为你一开始没有提到。


推荐阅读