0

I have a MySQL and PHP script to enter a row when it doesn't exist.

INSERT INTO `tblPlayerAchievements` (HS_ID, AchievementID, AchievementProgress) 
SELECT * FROM (SELECT ".$userData['HS_ID'].", ".$achievementID.", 0) AS tmp 
WHERE NOT EXISTS (SELECT * FROM `tblPlayerAchievements` 
WHERE HS_ID=".$userData['HS_ID']." AND AchievementID=".$achievementID.") 
LIMIT 1

This works perfectly until both $userData['HS_ID'] and $achievementID are the same value and then it skips that one. How do I fix this?

6
  • 1
    This sounds like a very convoluted way of doing something very simple. Commented Dec 6, 2014 at 0:12
  • I need to enter the row if it doesn't exist. How else do I do it, if not this way? Commented Dec 6, 2014 at 0:16
  • What do you need to do if it does exist? Commented Dec 6, 2014 at 0:17
  • Once its entered into the database I can then use that info. I'm storing achievement progress in the database. I can then reload that achievement progress later down the line. Commented Dec 6, 2014 at 0:21
  • why don't u check if the record doesn't exist first before insert it? Commented Dec 6, 2014 at 0:24

1 Answer 1

1

Since you haven't bothered answering the question about what happens if the row exists, I'm going to assume that you want the INSERT to fail. In that case, all you need to do is create a UNIQUE index on (HS_ID, AchievementID). I also recommend that you set a default value of 0 on AchievementProgress so that your query only needs to specify the IDs to create the row.

Sign up to request clarification or add additional context in comments.

5 Comments

I did answer why I needed it inserted. So I could recall the information later. -- EDIT Oh sorry I misread you're comment. Yeah I need it to fail if it does exist.
HS_ID and AchievementID are concatenated primary key. It works on ALL other entries until HS_ID and AchievementID are the same value. That insert then fails.
So then... what exactly do you want the query to do?
I want it to insert the query if it does not exist. If it does exist, it should fail. I already have HS_ID and achievementID as concatenated primary keys. I don't know why its skipping when HS_ID and AchievementID are the same value.
I don't understand why you're doing that huge mass of a query then. An INSERT will fail if the fields in a unique key have values that already exist in the table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.