Codeigniter - handling errors when using active record


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)

11/22/2015 8:19:00 PM

Accepted Answer

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
2/5/2010 6:53:49 AM

Straight from the CodeIgniter support forum:

$res = $this->db->query($str);

if (!$res) {
  // if query returns null
  $msg = $this->db->_error_message();
  $num = $this->db->_error_number();

  $data['msg'] = "Error(".$num.") ".$msg;

Note that you can also log Active Record errors by going into your CI app config file and setting the following:

$config['log_threshold'] = 1;

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