Jack UK
Jack UK

Reputation: 45

How to Prevent Same Record / Twice MySQL - PHP

I use a 3rd party payment solution on my app.

After a member make a payment (3-4 seconds), 3rd party payment site will redirect the member our web site.

At the same time, payment site sends a request to our web site about every payment.

If payment info request coincides with redirect user request, the system saves two times. To prevent twice recording, I use an unique ID on DB for every payment.

$unique_id = $_GET['unique_id'];
## ask the DB this this unique ID exist?
if($exist){
  //update some tables
  //delete the unique id 
}
else{
   //it was done before
}

Let's say the unique ID asd89279182jkfhff1249879 if two same request come to our web site at the same second and unique id is exist, the script will do job twice.

mywebsite.com/a.php?unique_id=asd89279182jkfhff1249879

How can I prevent twice record for this situation?

Upvotes: 0

Views: 576

Answers (2)

sedhossein
sedhossein

Reputation: 19

You could UPSERT values to your table. We can imitate MySQL UPSERT in one of these three ways:

  1. UPSERT using INSERT IGNORE
  2. UPSERT using REPLACE
  3. UPSERT using INSERT with ON DUPLICATE KEY UPDATE

or set PRIMARY KEY and UNIQUE Index for your id can prevent duplicating in your data

Upvotes: 0

tadman
tadman

Reputation: 211590

Normally you don't test and then insert, you just insert and check for errors because you've set up a UNIQUE constraint on that column.

If you try and insert into a table where that unique value is already taken you'll get an error of the "duplicate key" variety. It's actually impossible to add two with the same ID.

You can also do things like add an ON DUPLICATE KEY clause to define additional behaviour, like to update the record with new data.

Upvotes: 1

Related Questions