Logan
Logan

Reputation: 1147

INSERT command inserting duplicates

I am writing a quiz website.
What should happen is:

I don't think it should matter, but later on on the code, it queries the database with the SELECT command.
When i run this code, it seems to enter 2 or 3 entries to the database. The trend seems to be that when i run the code it enters the previous answer, followed by the new answer. Any help would be greatly appreciated. Thanks,

Logan

Upvotes: 0

Views: 226

Answers (3)

Jeremy Raymond
Jeremy Raymond

Reputation: 6027

Another option would be to first try to retrieve the data you're about to enter into the database. If you find it, it's already there, so don't add it again. The suggestions for using constraints are sound but if the data you're trying to prevent duplicates of isn't easily added to the constraints or the data you don't want duplicates of is not exactly the same data (say just similar data) then this is another option.

Upvotes: 1

Brimstedt
Brimstedt

Reputation: 3140

The unique constraint mentioned by cmptrgeekken should definately be added if you only allow one answer per user, but then you must also handle the primary key violation if it occurs: Inform the user it has already replied OR replace the previous value, depending of how you want the site to work.

Also, Is for some reason the request triggered more than once? Maybe by javascript, or some other logic of yours? If duplicate answers appears when you only click once, this seems to be the case.

/B

Upvotes: 0

cmptrgeekken
cmptrgeekken

Reputation: 8092

It seems like what you want to do is to allow only one answer per question per user. If that's the case, you'll want a UNIQUE constraint on your table on userid and qid:

ALTER TABLE answers ADD UNIQUE(userid,qid);

This will result in an error when you try to insert a row with the same userid and qid. If you want to allow users to change their error, you can change your INSERT query to:

INSERT INTO answers (userid ,answer ,qid) VALUES ($uid, '$answer', $qid) ON DUPLICATE KEY UPDATE answer='$answer'

This will prevent multiple records from showing up in the database, but multiple INSERTs might still be called from your PHP code. To fix that, we'd have to see some more of your code.

Upvotes: 1

Related Questions