在以下代码中,事务失败并调用回滚。
然而,就产出而言:
如果我删除closeCursor(),付款人的余额将打印为-200 $。
如果我指定closeCursor(),付款人的余额将打印为0,这是预期的行为。
这是因为第一个select语句的结果在第二个语句运行之前没有被清除。
为什么我们需要关闭回滚的连接以反映在输出中?在这两种情况下,都会调用回滚,因此在DB中指定值0。所以我希望余额打印为0.
我没有看到关闭连接数据库和获取最新数据库值之间的关系。 Fetch()从DB获取值,所以如果值为0,那么“它认为”它是怎么回事?
这仅适用于SQLite。无论你是否使用closeCursor(),MySQL都会打印0。
<?php
try {
require_once '../../includes/pdo_connect.php';
// Set up prepared statements transfer from one account to another
$amount = 0;
$payee = 'John White';
$payer = 'Jane Black';
$debit = 'UPDATE savings SET balance = balance - :amount WHERE name = :payer';
####1st SQL#### $getBalance = 'SELECT balance FROM savings WHERE name = :payer';
$credit = 'UPDATE savings SET balance = balance + :amount WHERE name = :payee';
$pay = $db->prepare($debit);
$pay->bindParam(':amount', $amount);
$pay->bindParam(':payer', $payer);
$check = $db->prepare($getBalance);
$check->bindParam(':payer', $payer);
$receive = $db->prepare($credit);
$receive->bindParam(':amount', $amount);
$receive->bindParam(':payee', $payee);
// Transaction
$db->beginTransaction();
$pay->execute();
if (!$pay->rowCount()) {
$db->rollBack();
$error = "Transaction failed: could not update $payer's balance.";
} else {
// Check the remaining balance in the payer's account
$check->execute();
$bal = $check->fetchColumn();
########## $check->closeCursor();
// Roll back the transaction if the balance is negative
if ($bal < 0) {
$db->rollBack();
$error = "Transaction failed: insufficient funds in $payer's account.";
} else {
$receive->execute();
if (!$receive->rowCount()) {
$db->rollBack();
$error = "Transaction failed: could not update $payee's balance.";
} else {
$db->commit();
}
}
}
} catch (Exception $e) {
$error = $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDO Transaction</title>
<link href="../../styles/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>PDO Transactions</h1>
<?php
if (isset($error)) {
echo "<p>$error</p>";
}
?>
<table>
<tr>
<th>Name</th>
<th>Balance</th>
</tr>
####2nd SQL####<?php foreach ($db->query('SELECT name, balance FROM savings') as $row) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td>$<?php echo number_format($row['balance'], 2); ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
答案 0 :(得分:0)
Ryan Vincent的上述回复是正确的。
所以我指定这个以将我的问题标记为已解决。
谢谢,
的Qwerty