1
I am implementing a code where there is a foreign key in two tables. Soon I tried several means and could not handle the error:
Error Number: 1451
Cannot delete or update a parent row: a foreign key constraint fails (`base`.`tableus`, CONSTRAINT `doctor_ibfk_1` FOREIGN KEY (`department_id`) REFERENCES `department` (`department_id`))
DELETE FROM `department` WHERE `department_id` = '1'
Filename: models/Crud.php
Line Number: 292
I’ve used an example I found Here and did not resolve.
I revising my question here, I missed an important detail, I do not want the user to delete the data from the table 'father' while having tables 'daughters' linked to it. Every time the user tries to do this he should get an error, in case I’m not able to handle this error in codeigniter.
function delete_department($department_id)
{
//verifica se recebe mensagem de erro na exclusão.
$verifica_erro = $this->db->_error_number() == 1451;
if ($this->delete_department($department_id) == $verifica_erro){
echo "Mensagem de erro para o usuário!";
}else{
//senão tiver executa a exclusão.
$this->db->where('department_id',$department_id);
$this->db->delete('department');
}
}
This code executes and brings another error:
Fatal error: Uncaught Typeerror: Argument 1 passed to Ci_exceptions::show_exception() must be an instance of Exception, instance of Error Given, called in /Path/system/core/Common.php on line 658 and defined in /Path/system/core/Exceptions.php:190 Stack trace: #0 /Path/system/core/Common.php(658): Ci_exceptions->show_exception(Object(Error)) #1 [Internal Function]: _exception_handler(Object(Error)) #2 {main} in thrown /Path/system/core/Exceptions.php on line 190
This is not with Codeigniter. This mistake comes from the bank. You are trying to delete or update a record in the parent table that has references in another table using FK. Tap your database settings and configure the records to be deleted/updated along with the main.
– ShutUpMagda
Okay, but in this case, I created this FK myself, to protect data integrity. I need to treat this error in codeigniter, ie for when the user tries to delete a department that is being used get a custom message and not the error above. I am unable to create this function.
– JB_