Codeigniter - handling errors when using active record

Sergio picture Sergio · Feb 5, 2010 · Viewed 42.2k times · Source

I am putting together a few models for my codeigniter site and can't seem to find any word in the documentation of how to handle errors that could occur when using the Active Record system.

The documentation demonstrates how to perform CRUD along with some relatively involved queries but no where along the line is error handling discussed. I have done a quick google search and it would appear that the Active Record classes do not throw exceptions. Is this the case? No try catch then...

So, how do you code to handle database errors in codeigniter? (failed connection, duplicate key, broken referential integrity, truncation, bad data types etc etc)

Answer

emmychan picture emmychan · Feb 5, 2010

Whether you're using the active record class or not, you can access database errors using $this->db->_error_message() and $this->db->_error_number().

If you're using a mysql database, these functions are equivalent to mysql_error() and mysql_errno() respectively. You can check out these functions by looking at the source code for the database driver for the database you're using. They're located in system/database/drivers.

So, after you run a query, you can check for errors using something like:

if ($this->db->_error_message()) \\handle error