Use Transaction in Slim


I use below code to insert or update my data:

$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']);

    $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);


How can i use transaction when want execute 4 query ?


Well, ideally you want to start your transaction when initializing your DB connection and then do a commit when the request finishes. This way, any request you handle will run in a transaction … if you get an exception, you can then catch the exception and do a rollback in order to cancel the transaction.

This approach ensures that your data remains consistent across requests even if something goes wrong.


I use $this->db->beginTransaction(); , $this->db->commit(); and $this->db->rollBack();


Hi @iMohammadi Have you tried my example from here?