如何在事务中 运行 多个 INSERT 查询并使用插入 ID?

How to run multiple INSERT queries in a transaction and use insert id?

我需要将数据插入到 3 table 中,并且需要将最后插入的查询的 ID 获取到 shopper table 中。我知道 运行

可以做到这一点
$conn -> insert_id;

在单个查询中,但在我的例子中,我需要创建一个带有回滚的事务,以防出现任何故障。像

$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);

$stmt1 = $conn->prepare("INSERT INTO shopper (usersID, parentJob, phoneNumber,address) VALUES (?, ?, ?, ?)");
$stmt1->bind_param("ssss", $userId, $parentJob, $phoneB, $addressB);

$stmt2 = $conn->prepare("INSERT INTO shipment (shipmentID, usersID,..) VALUES (?, ?, ?, ?)");
$stmt2->bind_param("ssss", $userId, ...);

$stmt3 = $conn->prepare("INSERT INTO address (addressID, usersID, ...) VALUES (?, ?, ?, ?)");
$stmt3->bind_param("ss", $userId, ...);

$conn->begin_transaction();
if ($stmt1->execute() && $stmt2->execute() && $stmt3->execute()) {
    $conn->commit();
} else {
    $conn->rollback();
}

$conn->close();

如您所见,我正在尝试将最后插入的 usersID 作为外键传递到 shipmentaddress table 中。那么当像

一样将所有这些一起提交时我该怎么做
if ($stmt1->execute() && $stmt2->execute() && $stmt3->execute()) {
    $conn->commit();
} else {
    $conn->rollback();
}

异常为交易提供了巨大的帮助。因此 configure mysqli to throw exceptions。不仅对于事务,而且因为它是一般情况下报告错误的唯一正确方法。

除了例外,您的代码将简单明了

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$conn->set_charset('utf8mb4');

$conn->begin_transaction();

$stmt = $conn->prepare("INSERT INTO shopper (usersID, parentJob, phoneNumber,address) VALUES (null, ?, ?, ?)");
$stmt->bind_param("sss", $parentJob, $phoneB, $addressB);
$stmt->execute();
$userId = $conn->insert_id;

$stmt = $conn->prepare("INSERT INTO shipment (shipmentID, usersID,..) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $userId, ...);
$stmt->execute();

$stmt = $conn->prepare("INSERT INTO address (addressID, usersID, ...) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ss", $userId, ...);
$stmt->execute();

$conn->commit();

如果出现错误,将抛出异常并自动回滚事务。