You first should check why you have a duplicated key.
You can use INSERT IGNORE command rather than the INSERT command.
If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
This should prevent you script form breaking.
Same exists for UPDATE -> UPDATE IGNORE,
But be very careful with this one.
You should verify if the update passed or not,
And act accordingly.