• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
easy way to catch database insert into errors to stop script from breaking?


So I have a database with a primary key set to auto inc, but also, a field which needs to be kept unique. I am inserting into the database via a script that will insert 20-100 fields at a time, and occasionally there will be a duplicate record which will throw an error if its already in the database, breaking the script.

So, is there an easy way in CI to catch the FAIL: INSERT INTO DUPLICATE ENTRY FOR KEY 2

Error, so that it will just say ok, that insert didnt work, but lets keep going?

P.S. I am aware the normal thing might be to check whether the key exists first, but I am working with an external API which makes it not as easy, and also I would think it would use up more resources to check whether it exists before running the script as duplicate entries are still fairly rare occurence.

Any help much appreciated.

Use IGNORE keyword in your insert. It will not insert row but will not return an error, only warning.

If you want to replace the row with new data use REPLACE instead of INSERT.

Ignoring errors is never a good idea.

I would set in system/application/config/database.php

$db['default']['db_debug'] = FALSE;

This will stop your script from breaking when you get an insert error.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.