在看这篇博客的时候,如果你有什么疑惑吗,可以参照一下这两篇博客
MySQLi面向过程实践---事务处理http://www.cnblogs.com/-beyond/p/7577232.html
PDO实现事务处理http://www.cnblogs.com/-beyond/p/7551177.html
MySQLi面向对象的事务处理涉及以下三个函数
public bool mysqli::begin_transaction ([ int $flags [, string $name ]] ) bool mysqli::commit ( void ) bool mysqli::rollback ( void )
示例代码如下:
最重要的莫过于关闭自动提交
1 <?php 2 $db=new mysqli("localhost","root","root","test"); 3 4 $db->begin_transaction(); 5 $db->autocommit(FALSE);//重要 6 try{ 7 $sql_1="delete from aaa where uid = 2;"; 8 $db->query($sql_1); 9 if($db->affected_rows<=0){ 10 throw new Exception("failed to delete data one\n"); 11 //如果操作一失败,则抛出异常,不会继续执行下个操作 12 } 13 14 $sql_2="delete from aaa where uid = 999"; 15 $db->query($sql_2); 16 if($db->affected_rows<=0){ 17 throw new Exception("failed to delete data two\n"); 18 //如果操作2失败,则抛出异常 19 } 20 21 if(!$db->commit()){ 22 throw new Exception("failed to commit\n"); 23 //如果提交操作出错,则抛出异常 24 } 25 echo "success to delete two data\n"; 26 } catch (Exception $e){ 27 $db->rollback(); 28 echo $e->getMessage(); 29 echo "haven‘t finish all works\n"; 30 } 31 32 $db->close(); 33 ?>
时间: 2024-10-06 06:13:04