I am currently developing an auction website as part of a portfolio project and I have come across an interesting problem which can’t seem to resolve.
At the moment I am currently checking the current highest bid (query 1) and then if the bid is higher than the one currently stored then I am inserting the new bid into the database (query 2). Fairly basic logic, and obviously if the bid is lower then the user will eventually be notified.
Query 1:
$result = mysql_query("SELECT * FROM bids WHERE item_id = '".$_POST['id']."' ORDER BY bids.amount DESC LIMIT 1");
Query 2:
$query = sprintf("INSERT INTO bids(item_id,buyer_id,amount,created) VALUES('%s','%s','%s',NOW())",
mysql_real_escape_string($item_id),
mysql_real_escape_string($user_id),
mysql_real_escape_string($amount));
Note: I know there are major security issues with this code but this is just an example…
However, I am uncertain if there will be a situation where between the gap of checking the price and inserting into the database, another query could infact go faster, insert into the database and then ruin the current bidding logic.
Will using transactions with the mysqli or PDO driver sufficient to ensure that the bids are queued correctly?
Does MySQL provide a method of queuing mysql queries to ensure that this will not happen?
A possible way is to use a
select for update, which if you disable the autocommit, lock the selected row. At this point, if the bid is higher, you insert the new bid and commit the transaction, if the bid is lower you can notify the user and rollback (or commit) the transaction