如果多个预准备语句中的一个失败,请停止并恢复

时间:2016-04-18 15:33:11

标签: php mysql mysqli

我有一个类数据库,它有多个方法,有些执行预处理语句,用于在我的表中创建新行。目前,一切正常,但如果出现问题,是否有办法停止进一步的查询并恢复之前的查询。

以下是我的表单当前处理方式的一个小例子:

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;

同样,如果其中任何一个失败,我想恢复所有查询并退出此表单处理。谢谢!

1 个答案:

答案 0 :(得分:3)

  1. 通过在mysqli connect

    之前添加此行,将mysqli置于异常模式
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
  2. 交易
  3. 中包裹您的查询
  4. 将您的交易包裹在try..catch语句中并在其中添加回滚调用。
  5. 所以代码就像

    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;
    }