php - 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);```
解决方案
我可以从外观中看出您一定遇到了 SQL 语法错误 - 您不能在同一个查询中使用INSERT...VALUES
和INSERT...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 如果你在运行代码的时候还有其他问题,你需要具体解释一下,因为你一开始没有提到。
推荐阅读
- java - 连接耳机时如何在Android中录制音频?
- google-apps-script - Google Apps - 在提交表单时 - 工作表的名称是什么
- php - 我正在寻找一种方法来允许网站访问者在我的网站上创建帖子(无需登录)
- c# - 如何使用 foreach 循环在同一行中显示 3 个引导卡标题
- kubernetes - 为 EKS 服务命名(而不是自动生成)
- hyperledger-fabric - 私人数据收集到底有什么意义?
- smartcard - 使用 APDU 列出 globalplatform 智能卡的内容
- c# - 更改 Swagger 属性名称
- python - 为什么 pd.date_range 返回一个空序列?
- angular - 用于由斜线分隔的路径的 Ionic 4 通配符路由