0

I have a table with millions of rows:

id | info | uid

The uid is null by default. I want to select 10 rows and assign them to a uid, but I want to avoid any potential concurrency issues. So I think the only way to do that is to somehow select 10 rows based on certain criteria, lock those rows and then make my changes before unlocking them.

Is there a way to do row-locking in MySQL and PHP? Or is there some other way I can gaurantee that this doesnt happen:

  1. user a queries the table where uid is null
  2. finds row 1
  3. user b queries the table where uid is null
  4. finds row 1
  5. user a process row and sets it back to null
  6. user b process row and sets it back to null

See my problem?

rockstardev
  • 13,479
  • 39
  • 164
  • 296
  • Search is your friend, possible duplicate of [PHP / MySQL - how to prevent two requests \*Update](http://stackoverflow.com/a/15027067/342740) – Prix Nov 07 '14 at 21:37
  • possible duplicate of [PHP / MySQL - how to prevent two requests \*Update](http://stackoverflow.com/questions/15026825/php-mysql-how-to-prevent-two-requests-update) – Mike Brant Nov 07 '14 at 21:46
  • Just want to know, did you solve your problem? – ForguesR Jul 02 '15 at 15:21

1 Answers1

0

What you probably need is SELECT ... FOR UPDATE. With this, retrieved rows are locked until a COMMIT or a ROLLBACK is made. So you can do something like :

START TRANSACTION;

SELECT * FROM yourTable WHERE uid IS NULL FOR UPDATE;

-- UPDATE to whatever you want

COMMIT;
ForguesR
  • 3,558
  • 1
  • 17
  • 39