Best Practices for Processing Errors from Database in CodeIgniter


I have a table with a unique key (date + userid) in my web application database. When I try to insert record with existing date and userid I receive the following error:

dupicate key in table

I turned on the database debugger in application config, because I needed to use MySQL error numbers and messages. Now I need to process this error. I can use hard coded constants in the controller, but I think it's not good idea. I need database error handling in many places, and I dont like CodeIgniter's error handling. What is a best practice concerning the processing of database errors.

12/31/2011 11:05:57 AM

We use in our project constructions like these:


but this undocumented functions and in next releases this could change. Of course you can simply use standard php for mysql error handle function:


internally CI use these functions.

As for me the best practice is use in custom Model's base class (BaseModel)


and determine error, next throw exception with information error message taken from


All your Model derived from BaseModel, and call method to check last request for db error and your Model must handle exception, and process it (may be additionally log), of course you can implement check result as result value and avoid of throwing exception.

1/22/2013 6:07:54 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow