Question

I'm using InnoDB.

I have table A

ID | DATA
1  | Something
2  | something else

table B

user_id | DATA
1       | NULL

my program reads a row from table A and updates table B, then deletes the row from table A after the update statement.

is it possible for two users (2 different concurrent sessions) to read the same row from table A? how can I avoid that?

that's my program

$core = Database::getInstance();
$q = $core->dbh->prepare("SELECT * FROM `tableA` LIMIT 1");
$q->execute();
$result = $q->fetch();

$q = $core->dbh->prepare("UPDATE `tableB` SET `data` = ? where `user_id`= ?");
$q->execute(array($result['data'],$ID));

// how to prevent a second user from reading the same row before the next statement gets executed

$q = $core->dbh->prepare("DELETE FROM `tableA`  where `ID`= ?");
$q->execute(array($result['ID']));
Was it helpful?

Solution 2

You can SELECT ... FOR UPDATE which puts an exclusive lock onto the row (at least if the transaction isolation level is set to somewhat reasonable).

This only works if the storage engine of the table is InnoDB. Also you have to execute all queries inside of the same transaction (so execute BEGIN query at the beginning and COMMIT at the end).

OTHER TIPS

Hope this helps and makes clear the view of what you want to achieve.

https://dev.mysql.com/doc/refman/5.0/en/internal-locking.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top