Example Method for Performing Transactions in the thinkPHP Framework

  • 2021-10-13 06:53:23
  • OfStack

This article illustrates the method of executing transactions in thinkPHP framework. Share it for your reference, as follows:


function tran(){
  // Defines flags for success and failure of transactions 
  $mark = true;
  //1.  Instantiation model 
  $model = D('student');
  //2.  Open a transaction 
  $model->startTrans();
  //3. ls Decrease 2000
  $sql = "update student set money=money-2000 where uname='ls'";
  $result = $model->execute($sql);
  // Judge sql Is the execution successful , If it fails, the $mark Replace with false
  if(!$result){
    $mark = false;
  }
  //4. zs Increase 2000
  $sql = "update student set money=money+2000 where uname='zs'";
  $result = $user->execute($sql);
  // Judge sql Is the execution successful , If it fails, the $mark Replace with false
  if(!$result){
    $mark = false;
  }
  $mark = false; // Temporarily forced to change false Test the rollback effect 
  //5.  Commit transaction 
  // Judge $mark Value of , For ture Is submitted for false Then rollback 
  if($mark){
    $user->commit();
  } else {
    $user->rollback();
  }
}

Transaction-related methods in TP: all defined in Model. class. php

startTran() Open a transaction

Commit() Commit a transaction

Rollback() : Rollback

When the transaction to be executed is in a different sql table, only the model definitions of the two sql need to be executed differently

Readers who are interested in thinkPHP can check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: