用一组新的PHP插件实现以MySQL为基础的事务

开发者在线 Builder.com.cn 更新时间:2006-09-11作者:Builder 来源:

工作实例

要了解这个在实践中是怎么工作的,让我们回到前面讨论过的银行转帐的例子.我们假设你的任务是建立一个简单的Web应用程序,让用户在他们的银行帐户间转帐。我们再进一步假设一个单独用户的帐户存储在一个MySQL数据库中,如下所示:

mysql> SELECT * FROM accounts;

+----+------------+---------+

| id | label      | balance |

+----+------------+---------+

|  1 | Savings #1 |    1000 |

|  2 | Current #1 |    2000 |

|  3 | Current #2 |    3000 |

+----+------------+---------+

3 rows in set (0.34 sec)

现在,需要建立一个简单的界面,使用户能够输入一个现金数额,实现从一个帐户到另一个的转帐。实际的“交易”将用两个UPDATE语句来执行,一个将转帐金额从源帐户取出,即借方,另一个将转帐金额记入目标帐户,即贷方。假设我们所做的是在帐户之间进行转帐,那么所有帐户的可用结余总额(00)应该一直保持不变。

列表B显示了可能的代码:

列表 B
<?php
// connect to database
$dbh = mysqli_connect("localhost", "user", "pass", "test") or die("Cannot connect");

// turn off auto-commit
mysqli_autocommit($dbh, FALSE);

// look for a transfer
if ($_POST['submit'] && is_numeric($_POST['amt'])) {
    // add $$ to target account
    $result = mysqli_query($dbh, "UPDATE accounts SET balance = balance + " . $_POST['amt'] . " WHERE id = " . $_POST['to']);
    if ($result !== TRUE) {
        mysqli_rollback($dbh);  // if error, roll back transaction
    }
   
    // subtract $$ from source account
    $result = mysqli_query($dbh, "UPDATE accounts SET balance = balance - " . $_POST['amt'] . " WHERE id = " . $_POST['from']);
    if ($result !== TRUE) {
        mysqli_rollback($dbh);  // if error, roll back transaction
    }

    // assuming no errors, commit transaction
    mysqli_commit($dbh);
}

// get account balances
// save in array, use to generate form
$result = mysqli_query($dbh, "SELECT * FROM accounts");
while ($row = mysqli_fetch_assoc($result)) {
    $accounts[] = $row;
}

// close connection
mysqli_close($dbh);
?>
<html>
<head></head>
<body>

<h3>TRANSFER</h3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Transfer $ <input type="text" name="amt" size="5"> from

<select name="from">
<?php
foreach ($accounts as $a) {
    echo "<option value="" . $a['id'] . "">" . $a['label'] . "</option>";   
}
?>
</select>

to

<select name="to">
<?php
foreach ($accounts as $a) {
    echo "<option value="" . $a['id'] . "">" . $a['label'] . "</option>";   
}
?>
</select>

<input type="submit" name="submit" value="Transfer">

</form>

<h3>ACCOUNT BALANCES</h3>
<table border=1>
<?php
foreach ($accounts as $a) {
    echo "<tr><td>" . $a['label'] . "</td><td>" . $a['balance'] . "</td></tr>";   
}
?>
</table>
</body>
</html>

用户评论

  • 用户名
  • 评论内容