我有一个类数据库,它有多个方法,有些执行预处理语句,用于在我的表中创建新行。目前,一切正常,但如果出现问题,是否有办法停止进一步的查询并恢复之前的查询。
以下是我的表单当前处理方式的一个小例子:
if(isset($_POST["someSubmitName"]) :
//post variables
....
// Start Queries
$db->address_table_insert_statement($firstName, $lastName, $companyName, $streetAddress, $streetAddress2, $streetAddress3, $city, $state, $zip, $country, $phone, $fax, $email, $date, $date);
$addressId = mysqli_insert_id($db->connection);
$db->address_table_insert_statement($firstName, $lastName, $companyName, $billingStreetAddress, $billingStreetAddress2, $billingStreetAddress3, $billingCity, $billingState, $billingZipCode, $billingCountry, $billingPhone, $billingFax, $billingEmail, $date, $date);
$billingAdressId = mysqli_insert_id($db->connection);
$db->account_table_insert_statement($active, $addressId, $billingAddressId, $dateCreated, $dateModified);
endif;
同样,如果其中任何一个失败,我想恢复所有查询并退出此表单处理。谢谢!
答案 0 :(得分:3)
通过在mysqli connect
之前添加此行,将mysqli置于异常模式mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
所以代码就像
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(...);
...
try {
$db->autocommit(FALSE);
$db->address_table_insert_statement($firstName, $lastName, $companyName, $streetAddress, $streetAddress2, $streetAddress3, $city, $state, $zip, $country, $phone, $fax, $email, $date, $date);
$addressId = mysqli_insert_id($db->connection);
$db->address_table_insert_statement($firstName, $lastName, $companyName, $billingStreetAddress, $billingStreetAddress2, $billingStreetAddress3, $billingCity, $billingState, $billingZipCode, $billingCountry, $billingPhone, $billingFax, $billingEmail, $date, $date);
$billingAdressId = mysqli_insert_id($db->connection);
$db->account_table_insert_statement($active, $addressId, $billingAddressId, $dateCreated, $dateModified);
$db->commit();
} catch (\Exception $e) {
$db->rollback();
throw $e;
}