Jump to content

Table locking doesn't prevent duplicate INSERT


cmayo

Recommended Posts

Hi all,

 

I\'m working through an issue that I\'m sure lots of people have already figured out, locking a table during a series of INSERTS to prevent duplicate entries:

 

OS Solaris 8

PHP 4.2.3

MySQL 3.23.53

Table type: MyISAM

 

The scenario is this:

 

1) A user submits a form containing about a hundred form fields.

 

2) MySQL is busy doing a lengthy SELECT for someone else, so the user\'s browser hangs until the SELECT is done.

 

3) The user gets tired of waiting and hits submit again while his browser is still hung.

 

4) When the long SELECT finishes, two PHP threads kick off, the user\'s original submit and his second, resulting in duplicate INSERT\'s

 

The first thing I tried was locking the tables at the top of the insert loop then unlocking at the bottom, i.e.

 

 

<?



// Pseudocode



LOCK TABLES



foreach($form_field as $db_field) {

    INSERT INTO $table VALUES (\'$db_field\',\'$thread_id)

}



UNLOCK TABLES



?>

 

What I thought would happen is that one PHP thread would have to wait for the other because the first had locked the tables, resulting in:

 

INSERTED DATA, THREAD1

INSERTED DATA, THREAD1

INSERTED DATA, THREAD1



INSERTED DATA, THREAD2

INSERTED DATA, THREAD2

INSERTED DATA, THREAD2

 

Instead, the inserts from the two threads were still interleaved:

 

INSERTED DATA, THREAD1

INSERTED DATA, THREAD2



INSERTED DATA, THREAD1

INSERTED DATA, THREAD2



INSERTED DATA, THREAD1

INSERTED DATA, THREAD2

 

Seemed like locking the tables for the duration of the insert loops would do it but it didn\'t seem to. Can someone tell me the correct way to do this?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.