我想确认我正确使用MySQL事务来正确处理关键事件(没有种族错误等)
$mysqli->autocommit(FALSE);
$mysqli->query("UPDATE users SET balance=balance-$amount, transactions=transactions+1, sent=sent+$amount WHERE email='$email'");
$mysqli->query("UPDATE users SET balance=balance+$amount, transactions=transactions+1, recv=recv+$amount WHERE email='$address'");
$newBalanceQ = $mysqli->query("SELECT balance FROM users WHERE email='$email'");
$newBalance = $newBalanceQ->fetch_row()[0];
if($newBalance < 0){
$mysqli->rollback();
} else {
$mysqli->commit();
}
答案 0 :(得分:2)
或者,您可以在没有事务的情况下执行此操作,因为您可以将两个查询合并为一个UPDATE
语句,
UPDATE users
SET balance = balance - (CASE WHEN email = '$email' THEN $amount ELSE $amount * -1 END),
transactions = transactions + 1,
sent = (CASE WHEN email = '$email' THEN sent + $amount ELSE sent END),
recv = (CASE WHEN email = '$address' THEN recv + $amount ELSE recv END)
WHERE email IN ('$email','$address')
您正在使用MySQLi
,但您没有参数化该值,在这种情况下,您仍然容易受SQL Injection
攻击。