My code,
$dbc -> beginTransaction();
$dbc -> query("LOCK TABLES items WHERE id = " . $user['id'] . " WRITE");
$q = $dbc -> prepare("UPDATE items SET shrapnel = ?, bank = ? WHERE id = ?");
$q -> execute(array($user['shrapnel'] - $_POST['deposit'], $user['bank'] + $_POST['deposit'], $user['id']));
$dbc -> query("UNLOCK TABLES items WHERE id = " . $user['id'] . "");
$dbc -> commit();
Pretty simple really, need to make sure no one else can read or write to the values of the users row in the table. Need to make sure it rolls back if something goes wrong as well!
If I don’t explicity rollback and something fails, then the changes won’t take place?
And is this a sure way of making sure that while this statement is committed that no other users will be able to read or update these values as to avoid a complete disaster?
I am using InnoDB which supports row level locking.
You can’t lock part of a table like that. You either lock the table or not with
LOCK TABLESTo lock certain rows for writing add
FOR UPDATEto yourSELECTlike this:And don’t do the
UNLOCK TABLES, just commit or rollback the transaction and the locks will be released.