交易是否正确?

时间:2018-04-29 07:04:34

标签: pdo transactions

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

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

我需要使用try block吗?如何在此查询中对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;

1 个答案:

答案 0 :(得分:0)

看看这个伪代码。 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
}