NYCPHP Meetup

NYPHP.org

[nycphp-talk] Inserting duplicate SQL primary keys

Allen Shaw ashaw at polymerdb.org
Wed Jul 25 16:16:28 EDT 2007


Cliff Hirsch wrote:
> While testing, I just did a page refresh, which caused this action to be
> repeated:
> 
> $query_string = "INSERT INTO task_category (task_id, category_id) VALUES
> ($taskId, $categoryId)";
> $this->dbManager->DbQuery($query_string);
> 
> Obviously, on the page refresh, it threw an error (DB Error: already
> exists), since it was already inserted.
> 
> The question:
> 
> Where should I be checking for this? Should I just suppress the error with
> @$this->dbManager->DbQuery($query_string);? Should I just do a select
> before-hand to see if the join is already in the table? Other ideas?
> 

Seems like the real problem here is that the application itself is not 
aware of which requests have been submitted already and which haven't. 
Of course you could do some things to skip out the error (error 
supression with @, using "insert IGNORE into ..." to prevent errors on 
duplicate keys, etc.), but I think you will make your life easier by 
addressing the root of the problem: if the page is reloaded, make sure 
the code isn't run a second time, unless that's what's supposed to happen.

In my systems, I'll assign a unique ID (based on microtime) to each 
submitted request (added as a hidden input in forms, else appended to 
the query string), to be stored in the database.  For each request, the 
system checks to see if the ID has been submitted; if so, the action 
code is skipped and only the display code is run; if not, the request ID 
is recorded in the databse, and the action code is processed as normal. 
  Garbage collection routines keep the request-ID cache from getting too 
big but keep the contents long enough to avoid false negatives.

That's just one way to do it.  Others here can probably recommend better 
methods, but I think you have to find some way to do it.  You probably 
don't want to go down the path of just supressing errors all over the 
place, because when a real error surfaces you need to be able to see it 
and handle it properly.

- Allen



-- 
Allen Shaw
slidePresenter (http://slides.sourceforge.net)



More information about the talk mailing list