如何使用 php 应用 MySQL 交易功能?

How can I apply MySQL transactions feature using php with it?

我正在尝试构建一个销售发票页面,该页面将多种产品作为输入以及一些有关客户的信息。它与四个 MySQL 表(销售、sale_details、发布和 product_inventory)交互。您将了解如果查询失败会发生什么。我想避免这种情况。为此,我尝试使用 PHP 和 MySQL (PHPMyAdmin) 来实现 InnoDB 数据库引擎的事务功能。另一个问题是我听说默认情况下 autocommit 是关闭的,我是否需要在每次触发查询时将其打开 ON 然后 OFF?这是我的 PHP 代码片段:

  $sal_date = trim($_POST["sale_date"]);
  $cust_id = trim($_POST["cust_id"]);
  $book_no = trim($_POST["sal_book_no"]);
  $rem = $_POST["sal_remarks"];
  $st = trim($_POST["sub_total"]);
  $disc = floatval($_POST["total_disc"]) + floatval($_POST["adj_disc"]);
  $total = trim($_POST["grand_total"]);

  $query1 = mysqli_query($link, "INSERT INTO sales
  (cust_id, book_no, sale_date, sub_total, discount, total, remarks)
  VALUES ('$cust_id', '$book_no', '$sal_date', '$st', '$disc', '$total', '$rem')") or die(mysqli_error($link));

  $query2 = mysqli_query($link, "SELECT LAST_INSERT_ID() as last_row") or die(mysqli_error($link));
  $sal_id = mysqli_fetch_array($query2);
  $sal = intval($sal_id["last_row"]);

  $the_query1 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `debit`) VALUES ('SI','$cust_id','$sal', '$sal_date', '$total')") or die(mysqli_error($link));
  $the_query2 = mysqli_query($link, "INSERT INTO `posting`(`type`, `account_id`, `tr_id`, `tr_date`, `credit`) VALUES ('SI','10002','$sal', '$sal_date', '$total')") or die(mysqli_error($link));

  for($count=0; $count<$_POST["total_item"]; $count++)
  {
    $prod_id = floatval(trim($_POST["product_name"][$count]));
    $quantity = floatval(trim($_POST["qty"][$count]));
    $disc = floatval(trim($_POST["disc"][$count]));

    $query3 = mysqli_query($link, "INSERT INTO sale_details (sal_id, prod_id, quantity, discount) VALUES ('$sal', '$prod_id', '$quantity', '$disc')") or die(mysqli_error($link));
    $query4 = mysqli_query($link, "INSERT INTO product_inventory (invoice_id, product_id, qty_out, in_date) VALUES ('$sal', '$prod_id', '$quantity', '$sal_date')") or die(mysqli_error($link));
  }

我会感谢你的建议。

你可以用这个方法

mysqli_query($db, "START TRANSACTION");

$query1 = mysqli_query($db, "Query 1");
$query2 = mysqli_query($db, "Query 2");
$query3 = mysqli_query($db, "Query 3");

if($query1 && $query2 && $query3) {
    mysqli_query($db, "COMMIT");
} else {
    mysqli_query($db, "ROLLBACK");
}