Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch DB errors in CodeIgniter PHP

I am new to CodeIgniter, PHP and MySQL. I want to handle the DB generated errors. From one of the post in Stackoverflow, I knew that by following statement one can catch the error.

 $this->db->_error_message();

But I cannot figure out the exact syntax of using that. Suppose I want to update the records of table named "table_name" by the following statement:

$array['rank']="8";
$array['class']="XII";
$this->db->where('roll_no',$roll_no);
$this->db->update("table_name", $array);

Here in the above code I want to catch the DB error whenever any DB level violation occurs i.e. either field name is not valid or some unique constraint violation occurs. If anyone helps me to fix that I would be really grateful. Thank you.

like image 768
Joy Avatar asked Jul 29 '13 11:07

Joy


3 Answers

You can debug the database error on database configuration in (config/database.php) like this:

$db['default']['db_debug'] = TRUE;

More info read here

Also you can use Profiler to see all the queries and their speed. In controller you can put this:

$this->output->enable_profiler(TRUE);

More information read here

like image 53
Erman Belegu Avatar answered Nov 19 '22 16:11

Erman Belegu


codeIgniter has functions for it

$this->db->_error_message(); 
$this->db->_error_number(); 


if(!$this->db->update("table_name", $array))
{
    $this->db->_error_message(); 
    $this->db->_error_number(); 
}
like image 5
Rajeev Ranjan Avatar answered Nov 19 '22 17:11

Rajeev Ranjan


On Codeigniter version 2,

$this->db->_error_message(); 
$this->db->_error_number();

On Codeigniter version 3,

$db_error = $this->db->error();
echo '<pre>';print_r($db_error);echo '</pre>';
like image 2
Sultan Avatar answered Nov 19 '22 16:11

Sultan