处理此问题的最佳方法是处理异常(一如既往,该死的 PHP 错误/警告内容)。仅仅是因为我们的commit()
调用也可能失败。请注意,finally
仅在较新的 PHP 版本中可用。
<?php
// Transform all errors to exceptions!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection = new \mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$connection->autocommit(false);
$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$stmt->execute();
// We can simply reuse the prepared statement if it's the same query.
//$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
// We can even reuse the bound parameters.
//$stmt->bind_param("ssi", $name, $gender, $age);
// Yet it would be better to write it like this:
/*
$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?), (?, ?, ?)");
$stmt->bind_param("ssissi", $name, $gender, $age, $name, $gender, $age);
*/
$stmt->execute();
$connection->commit();
}
catch (\mysqli_sql_exception $exception) {
$connection->rollback();
throw $exception;
}
finally {
isset($stmt) && $stmt->close();
$connection->autocommit(true);
}