0

我正在使用Phalcon,并且在 MySql 中有一个数据库。我在数据库中有三个表:

  • 用户:id,姓名,已售出
  • 公司:身份证、姓名、费用
  • 交易:id_company、id_user、成本

如果有足够的钱(已售出),用户必须进行交易。所以我必须这样做:

Step 1:
retrieve the sold of the user:
select sold
from user
where id='Charlie'

Step 2:
retrive the cost from the company:
select cost
from company
where id='Tango'

Step 3:
to check if the user has enough money:
if (sold-cost >= 0)
create the transaction
else
do not create the transaction.

我的问题是:有没有办法阻止数据库以便在没有数据库的情况下执行三个步骤可以改变?

我想这样做:

lock db
step 1
step 2
step 3
unlock db

但我还没有找到解决方案。

4

1 回答 1

1

我不确定它是如何在 Phalcon 框架中实现的,但 PDO 扩展实现的事务在这里可能会有所帮助:

<?php
$pdo->beginTransaction();
$stmt = $pdo->prepare('select sold from user where id= ?');
$stmt->execute(['Charlie']);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$sold = $row['sold'];

$stmt = $pdo->prepare('select cost from company where id= ?');
$stmt->execute(['Tango']);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

$cost = $row['cost'];

printf("Sold: %d, Cost: %d", $sold, $cost);

if ($sold >= $cost) {
    //reduse user sold
    $stmt = $pdo->prepare('update user set sold = sold - ? where id= ?;');
    $stmt->execute([$cost, 'Charlie']);

    // write transaction
    $stmt = $pdo->prepare('insert into transactions values (?, ?, ?);');
    $stmt->execute(['Charlie', 'Tango', $cost]);
    $pdo->commit();
} else {
    $pdo->rollBack();
}


$stmt = $pdo->prepare('select * from transactions');
$stmt->execute();
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($transactions);

PHP PDO 在这里摆弄

于 2021-10-25T12:46:51.623 回答