CodeIgniter Forums

Full Version: easy way to catch database insert into errors to stop script from breaking?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]lexusgs430[/eluser]
Hi,

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.

El Forum

[eluser]cahva[/eluser]
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.

El Forum

[eluser]rbnc[/eluser]
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.