【问题标题】:it is correct for a transaction?交易是否正确?
【发布时间】:2018-10-09 14:02:42
【问题描述】:

我使用 pdo 创建了一个 mysql 事务。

请检查我的代码是否完美。如果它不正确,那么我如何正确设置交易。

我需要使用 try 块吗?我如何在这个查询中对 try 块进行排序

if(is_null($this->pdo)){
return false;
} else {
$pdo = $this->pdo;

$pdo->beginTransaction();

$stmt = $pdo->prepare("SELECT mallu FROM users WHERE id=? LOCK IN SHARE MODE");
$stmt->execute([$alpharef]);
$reseller = $stmt->fetch();
$stmt = null;


$stmt = $pdo->prepare("UPDATE users SET mallu = mallu - :cost WHERE id=:userid");
$stmt->bindParam(':cost', $cost, PDO::PARAM_STR);
$stmt->bindParam(':userid', $alpharef, PDO::PARAM_INT);
if (stmt->execute() != true) {
  $conn->rollBack();
  return false
}
$stmt = null;


$dates = date("d-m-Y");
$statos = 0;
$stmt = $pdo->prepare("INSERT INTO request (rtyp, num, amount, cost, typ, usr, refid, tm, dates, status) VALUES (:rtyp, :num, :amount, :cost, :typ, :usr, :refid, NOW(), :dates, :status)");
$stmt->bindParam(':rtyp', $retyp, PDO::PARAM_STR);
............................................................
if (stmt->execute() != true) {
  $conn->rollBack();
  return false
}
$stmt = null;
$pdo->commit();
$this->msg = 'Request sent successfully';
return true;

}
$pdo = null;

【问题讨论】:

    标签: pdo transactions


    【解决方案1】:

    看看这个伪代码。 Try + catch 帮助您处理失败的事务。您所要做的就是在您的一条 sql 失败时抛出新的异常。

    $pdo->beginTransaction();
    try{
        //DB_operation1
        if (result==false){ throw new Exception("...message1...");}
    
        //DB_operation2
        if (result==false){ throw new Exception("...message2...");}
    
        $pdo->commit();
    }catch(exception $e){
        $pdo->rollBack();
        //do something with thrown message
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 1970-01-01
      • 2012-12-05
      • 2014-07-22
      • 2016-01-20
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多