我使用以下代码插入或更新我的数据:
$app->post('/save_main_operation_info', function ($request) {
$returning_info = [];
try {
$input = $request->getParsedBody();
$this->logger->info("save_main_operation_info ->");
$this->logger->info(" operation_id:" . $input['operation_id']);
$this->logger->info(" register_date:" . $input['register_date']);
$this->logger->info(" driver_personnel_id:" . $input['driver_personnel_id']);
$sql = "INSERT INTO `main_operation`(`operation_id`, `register_date`, `personnel_id`, `implementation_date`) VALUES (:operation_id, :register_date, :personnel_id, :implementation_date)";
$query = $this->db->prepare($sql);
$query->bindValue("operation_id", $input['operation_id']);
$query->bindValue("register_date", $input['register_date']);
$query->bindValue("personnel_id", $input['driver_personnel_id']);
$query->bindValue("implementation_date", $input['register_date']);
$query->execute();
$returning_info["success"] = true;
} catch (\Exception $exception) {
$this->logger->error("save_main_operation_info ->");
$this->logger->error(" ->" . $exception->getMessage());
$returning_info["success"] = false;
$returning_info["error_message"] = $exception->getMessage();
}
return $this->response->withJson($returning_info);
});
当要执行4个或更多查询时如何使用事务? 我看到^,但无能为力。 谢谢
答案 0 :(得分:1)
在您的情况下,PDO负责数据库事务。这是一个示例:
$app->post('/save_main_operation_info', function ($request) {
$returning_info = [];
try {
$input = $request->getParsedBody();
// Start a new transaction
$this->db->beginTransaction();
$sql = "INSERT INTO `main_operation`(`operation_id`, `register_date`, `personnel_id`, `implementation_date`)
VALUES (:operation_id, :register_date, :personnel_id, :implementation_date)";
$query = $this->db->prepare($sql);
$query->bindValue('operation_id', $input['operation_id']);
$query->bindValue('register_date', $input['register_date']);
$query->bindValue('personnel_id', $input['driver_personnel_id']);
$query->bindValue('implementation_date', $input['register_date']);
$query->execute();
// execute more queries...
// ...
// Commit all transaction changes
$this->db->commit();
$returning_info['success'] = true;
} catch (\Exception $exception) {
// Roll back all transaction changes
$this->db->rollBack();
$returning_info['success'] = false;
$returning_info['error_message'] = $exception->getMessage();
}
return $this->response->withJson($returning_info);
});