49

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)

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Sergio
  • 9,761
  • 16
  • 60
  • 88

2 Answers2

58

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
emmychan
  • 1,618
  • 12
  • 8
  • 18
    FYI - This only works if your db_debug flag in the database config file is set to FALSE. By default its set to TRUE in a new installation of CI 2.1 – Felby Apr 05 '12 at 15:47
  • 1
    @emmychan: could we catch exception to handle DB error? Is it the same with your solution? Thanks – secretlm Apr 12 '13 at 04:47
  • FYI - With PostgreSQL 9.4 / CI 2.1.3, I note that `_error_number()` often (always?) returns empty string but `_error_message()` has a (possibly multiline) error message text. So, how to parse error in various locales? – user9645 Apr 02 '15 at 17:44
  • Thanks but how can I get the error message when db_debug flag is TRUE? – rostamiani May 05 '15 at 02:01
  • These methods have been removed in CodeIgniter version 3. Use $this->db->error() instead. – always-a-learner Jun 05 '17 at 06:11
12

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;
  $this->load->view('customers_edit_view',$data);
} 

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;
Peter Drinnan
  • 4,344
  • 1
  • 36
  • 29