PHP mysql事务用try catch错误处理

时间:2016-05-04 10:42:39

标签: php mysql

我在php中使用以下代码进行事务处理。但是有些查询已经提交,有些查询没有提交。

我需要完整的mysql php事务处理代码。

 try {
    require_once './DB/dbConnect.php';
    $conn->autocommit(FALSE);
    $sql = "DELETE FROM `grn_items` WHERE grn_no ='" . $Doc . "'";
    $result = $conn->query($sql);

    if (!$result) {
        $result->free();
        return $conn->error;
        //throw new Exception($conn->error);
    }
   $sq3 = "UPDATE `grn` SET `editBy` = '" . $editBy . "' ,grnAmount ='" .             
   $total . "'    WHERE grnNo ='" . $Doc . "'";
    $result3 = $conn->query($sq3);

    if (!$result3) {
        $result3->free();
        return $conn->error;
        //throw new Exception($conn->error);
    }
    $conn->commit();
    $conn->autocommit(TRUE);
    $conn->close();
    return "success";
} catch (Exception $ex) {
    $conn->rollback();
    $conn->autocommit(TRUE);
    return $ex;
}

1 个答案:

答案 0 :(得分:1)

以下一行

require_once './DB/dbConnect.php';

应该在try and catch之外,所以它应该是

require_once './DB/dbConnect.php';
 try {

    $conn->autocommit(FALSE);
    $sql = "DELETE FROM `grn_items` WHERE grn_no ='" . $Doc . "'";
    $result = $conn->query($sql);

    if (!$result) {
        $result->free();
        return $conn->error;
        //throw new Exception($conn->error);
    }
   $sq3 = "UPDATE `grn` SET `editBy` = '" . $editBy . "' ,grnAmount ='" .             
   $total . "'    WHERE grnNo ='" . $Doc . "'";
    $result3 = $conn->query($sq3);

    if (!$result3) {
        $result3->free();
        return $conn->error;
        //throw new Exception($conn->error);
    }
    $conn->commit();
    $conn->autocommit(TRUE);
    $conn->close();
    return "success";
} catch (Exception $ex) {
    $conn->rollback();
    $conn->autocommit(TRUE);
    return $ex;
}

因为您的变量$conn来自那里。