1

我想确认我正在正确使用 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();
}
4

1 回答 1

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.

于 2013-06-03T01:16:06.373 回答