Search code examples
phpmysqlconcurrencytransactions

What happen if 1 user login at 2 different browser/device and buying 1 item simultaneously?


So imagine i have a website (PHP + MYSQL) and my site have a login page and sell Banana, and my site also have "Credits" users can top up via paypal to add more credits.

Imagine user1 have $1 in their credits and 1 banana cost $1, What if user1 Login at 2 different devices and buying 1 banana simultaneously, does it count as 2 banana buyed or 1 banana buyed and another banana rejected ?

And if 2 banana is buyed, is that any way to prevent this MULTIPLE SIMULTANEOUSLY REQUEST ?


Solution

  • It would be good practice to do this process as a single transaction. That way, the data is read, processed and then created/updated in good timing. This in itself would be feasible as the two transactions would not run concurrently.

    ($pdo = new PDO))->beginTransaction();
    $read = $pdo->Prepare(“Some select statement”);
    $read->execute(array(‘someVal’));
    if(($row = $read->fetch(PDO::FETCH_OBJ)) && (float) $row->wallet >= 1.0) {
        $update = $pdo->Prepare(‘Some update wallet statement’):
        $update->execute();
        $create = $pdo->Prepare(“create a new transaction”);
        $create->execute(array(‘some val’));
    }
    $pdo->commit();
    

    Alternatively, or for extra precaution, you could implant a minor random wait time between scripts executing to prevent timed attacks but the network latency should stop this.

    Update: I want to touch on security. Although PDO (if used correctly with emulate prepares set to false) does prevent most common vulnerabilities like SQL injections, transactions are subject to race conditions. Ensure you limit the block chain and are following security procedures to ensure race conditions are limited.