How to handle MySQL deadlock error in CodeIgniter 3.x
Tried normal try catch option , but its not working
>Solution :
Here are the steps to handle mySQL deadlock in Codeigniter-3.
- Enable the $config[‘db_debug’] = TRUE
- Catch the deadlock error using try-catch. Use this CI_DB_mysqli_utility::DB_ERROR_DEADLOCK constant in Codeigniter to catch the error.
Sample code:
try{
//mysql query execution
}
catch(Exception $e){
if ($e->getCode() == CI_DB_mysqli_utility::DB_ERROR_DEADLOCK) {
// Handle deadlock error
// For example, retry the operation after a delay
sleep(2); // Sleep for 2 seconds before retrying
// Retry the database operation
} else {
// Handle other database errors
log_message('error', 'Database error: ' . $e->getMessage());
// Throw or handle the error as needed
}
}
These steps worked out for me.
———————— New Edit ———————————–
If you can’t edit the config value in production. You can set the config dynamically within your method by using the below function.
function set_db_debug($enable_db_debug) {
$CI =& get_instance();
$CI->config->load('config');
$CI->config->set_item('db_debug', $enable_db_debug);
}