0

Is it possible, when inserting a row with unique field, to change the value that goes into unique field into something different in case of duplicate?

Situation: a user is adding a new article, which name cannot be duplicate. For some reason, the user types the name that already exists in the database.

If using "ON DUPLICATE KEY UPDATE" - previous record (with the same name as inserted) gets all new data in other fields (update occurs) - not good.

What is required is, on insert, if the field is unique, and there is a match in DB, change the value being inserted into something like "[DUPLICATE] name".

This will reveal the presence of duplicate and the user will just change the name (which, likely, was inserted as duplicate by error).

4
  • Try the insert. If it fails, change the unique value and hit it again. Commented Aug 16, 2016 at 16:51
  • Is there a way to include intermediary (select... where name = "article name") into insert statement, so the select would produce either true (i.e. concatenate name with "[duplicate]" string) or false (the name is inserted as is)? Commented Aug 17, 2016 at 10:00
  • INSERT INTO ... SELECT ... FROM is a thing, so maybe? Commented Aug 17, 2016 at 13:57
  • 1
    INSERT INTO and SELECT is not possible due to mysql restriction (mysql docs: "you cannot insert into a table and select from the same table in a subquery"). Working solution at this moment: - go over all field names that are unique (known in advance); - if duplicate present in DB (i.e. count !=zero) - add timestamp to the value to be inserted/updated. A modified form of timestamp is used instead of a constant value to avoid making another duplicate, which name (i.e. 'name[dub]') is already present in DB from previous add/edit. Commented Aug 18, 2016 at 17:37

1 Answer 1

1

You have to do something like (using prepared statements with mysqli)-

 SELECT name FROM table WHERE name=?

Bind the variable (I am assuming $articleName) and store the result, then check if there is a match with mysqli_num_rows().

If there exists one or more rows, rename the article name.

 $articleName=$articleName."[DUPLICATE]";

Then insert into the db.

Note: There will usually be no same article names, because a sentence can be constructed in a many ways. Consider building a very smart program to detect that or manually check like they do in SO.

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

Comments

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.