Reputation: 344
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).
Upvotes: 0
Views: 1134
Reputation: 616
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.
Upvotes: 1