I was trying to upload a csv file to update a table in my db, but also wanted to prevent duplication. Initially a single DUPLICATE worked but when i added the second condition it didn’t work.
I got “Duplicate entry ‘1’ for key PRIMARY”. How can i achieve my aim.
thanks for your help.
$sql = "INSERT INTO biodata (student_number, fname, lname, course_name, level)
VALUES('$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]')
DUPLICATE KEY UPDATE student_number = student_number
AND course_name = course_name";
mysql_query($sql) or die (mysql_error());
Replace
ANDwith comma,in theUPDATEpart.Use the
VALUES()syntax to refer to the values passed.Also, you don’t need to update the Primary or Unique Key (that activated the
ON DUPLICATE KEY UPDATE):What the above code does:
If the
INSERTfails (there is already a student with thisstudent_numberyou are trying to Insert), theUPDATEis activated and the 4 other fields are updated.It’s your choice which fields to update. If you want to update for example, only the
course_namefield, just keep that line and remove the rest.