mysql事务的使用_如何正确使用MySQL事务

本文讨论了一个关于在不同页面中启动多个事务导致的问题,并提供了一种解决方案:通过自定义数据库连接类来模拟嵌套事务,确保即使在包含文件中也能正确处理开始和结束事务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bd96500e110b49cbb3cd949968f18be7.png

I need some help.

I have different files. For example:

index.php, news.php

include-scripts like: facebook.php, pay.php and more.

On all the pages (except news.php) a transaction is started at the beginning of the script, and ending at the end of the script.

On pages like index.php and news.php, I include pay.php. But the problem is: when I'm visiting index.php a transaction is already started, so now two transactions are active! But I can't remove the transaction-start from pay.php, because if I call the script from news.php there is no active transaction.

(My website is much more complex with many more pages and things).

Can someone help me please? Thanks!

解决方案

Your best bet is to emulate nested transactions. To do this write a wrapper for your database access.(pseduocode)

class MyMysqli {

protected $realDb;

protected $transaction_count =0;

public function __construct ($host, $username , $passwd, $dbname){

$this->realDb = new Mysqli($host, $username, $passwd, $dbname);

}

public function __get($property){

return $this->realDb->$property;

}

public function __set($property, $value){

return $this->realDb->$property = $value;

}

public function __call($method, $args){

return call_user_func_array(array($this->realDb, $method), $args);

}

// overload begin_transaction, commit and rollback

public function begin_transaction(){

$this->transaction_count++;

if ($this->transaction_count == 1){

$this->realDb->begin_transaction();

}

}

public function commit(){

$this->transaction_count--;

if($this->transaction_count == 0){

$this->realDb->commit();

}

}

public function rollback(){

throw new Exception("Error");

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值