I have a query that is supposed to return an error message like this:
Error Number: 1451
Cannot delete or update a parent row: a foreign key constraint fails (`sservice_dev_mercury`.`agent_accounts`, CONSTRAINT `agent_role_fk` FOREIGN KEY (`role`) REFERENCES `roles` (`id`))
DELETE FROM `roles` WHERE `id` = '3'
This is when db_debug is true. When I turned it false and used
$error = $this->db->error();
return $error;
I get error 0 with an empty message. Is there something I am missing when trying to get the errors? This is the query:
public function delete($id){
$this->db->trans_begin();
$this->db->where('id',$id);
$this->db->delete($this->table);
$this->db->trans_complete();
if($this->db->trans_status()===false){
$this->db->trans_rollback();
$error = $this->db->error();
return $error;
}else{
$this->db->trans_commit();
return true;
}
}
Can someone take a look and see if something went wrong?
The user has mentioned that he wants to get the error in the database transaction. so for that, I found only this solution to the problem, but It is quite verbose:
try {
$this->db->trans_begin();
$res = $this->db->where('id',$id)->delete($this->table);
if(!$res) throw new Exception($this->db->_error_message(), $this->db->_error_number());
$this->db->trans_commit();
}
catch (Exception $e) {
$this->db->trans_rollback();
log_message('error', sprintf('%s : %s : DB transaction failed. Error no: %s, Error msg:%s, Last query: %s', __CLASS__, __FUNCTION__, $e->getCode(), $e->getMessage(), print_r($this->main_db->last_query(), TRUE)));
}
Please note that
$this->db->_error_message(), $this->db->_error_number() after each query, because it returns an empty response in the catch block.This way you can achieve the detailed error handling.
Here is the reference link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With